Sunday, May 13, 2007

Campus_10 (C Question)

Find out the output of following:

1. main()
{
char string[]="Hello World";
display(string);
}
void display(char *string)
{
printf("%s",string);
}

Answer : 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.

2. main()
{
int m=- -2;
printf("m=%d",m);
}

Answer: m=2;
Explanation:
Here unary minus (or negation) operator is used twice.
maths rules applies, minus * minus= plus.


3. #define int char
main()
{
int k=65;
printf("sizeof(k)=%d",sizeof(k));
}

Answer: sizeof(k)=1
Explanation:
Since the #define replaces the string int by the macro char


4. main()
{
int m=10;
m=!m>14;
printf("m=%d",m);
}

Answer: m=0


5. #include
main()
{
char s[]={'a','b','c','\n','c','\0'};
char *q,*str,*str1;
q=&s[3];
str=q;
str1=s;
printf("%d",++*q + ++*str1-32);
}

Answer: 77
Explanation:
q is pointing to character '\n'. str1 is pointing to character 'a' ++*q. "q is pointing to '\n' and that is incremented by one." the ASCII value of '\n' is 10, which is then incremented to 11. The value of ++*q is 11. ++*str1, str1 is pointing to 'a' that is incremented by 1 and it becomes 'b'. ASCII value of 'b' is 98.
Now performing (11 + 98 – 32), we get 77("M"); So we get the output 77 :: "M" (Ascii is 77).

No comments: