Tuesday, January 17, 2012

Miscellaneous C OUTPUT

Question 1:
#include<stdio.h>
int main()
{
   unsigned int x = -1;
   int y = ~0;
   if(x == y)
      printf("same");
   else
      printf("not same");
   printf("\n x is %u, y is %u", x, y);
   getchar();
   return 0;
}
Output: “same x is MAXUINT, y is MAXUINT” Where MAXUINT is the maximum possible value for an unsigned integer.-1 and ~0 essentially have same bit pattern, hence x and y must be same. In the comparison, y is promoted to unsigned and compared against x. The result is “same”. However, when interpreted as signed and unsigned their numerical values will differ. x is MAXUNIT and y is -1. Since we have %u for y also, the output will be MAXUNIT and MAXUNIT.
Question 2:
main()
{
char string[]="Hello World";
display(string);
}
void display(char *string)
{
printf("%s",string);
}
Output:Compiler Error : Type mismatch in redeclaration of function display
Explanation:In third line, when the function display  is encountered, the compiler
doesn't know anything about the function display. It assumes the arguments and return
types  to be  integers,   (which  is  the default   type).  When  it  sees  the actual   function
display,  the arguments  and  type contradicts with what   it  has assumed previously.
Hence a compile time error occurs.
Question 3:
int main()
{
int c=- -2;
printf("c=%d",c);
}
Output:2
Explanation:Here unary minus  (or negation) operator  is used  twice.  Same maths
rules applies, ie. minus * minus= plus.
Note:
However you cannot  give like --2.  Because -- operator can   only be
applied  to variables as  a  decrement  operator   (eg.,   i--).  2  is a constant  and not  a
variable.

No comments:

Post a Comment