Follow Me on Twitter

Saturday, October 31, 2009

Solutions to C Puzzles 7

#include
int main()
{
int a=10;
switch(a)
{
case '1':
printf("ONE\n");
break;
case '2':
printf("TWO\n");
break;
defa1ut:
printf("NONE\n");
}
return 0;
}
If you expect the output of the above program to be NONE, I would request you to check it out!!

Solution:

Nothing gets printed. Bcs check the spelling of "defa1ut".
"The condition of a switch statement is a value. The case says that if it has the value of whatever is after that case then do whatever follows the colon. The break is used to break out of the case statements.Default is optional" Since none of the value is matched against case and no case has value 10 and compiler doesn't recognize "default" keyword above, nothing gets printed.

Explain the output of the following C program (No, the output is not 20).
#include
int main()
{
int a=1;
switch(a)
{   int b=20;
case 1: printf("b is %d\n",b);
break;
default:printf("b is %d\n",b);
break;
}
return 0;
}

Solution:
b is 9873931(some random junk value) since b is not initialized. the statement
int b=20; doesn't get executed bcs inside switch the execution starts from
case/default(if no case) block.

What would be the output of the following C program?
(Is it a valid C program?)
#include 
int main()
{
int i=43;
printf("%d\n",printf("%d",printf("%d",i)));
return 0;

Solution:
4321

printf returns the number of digits/characters it printed.So this
printf("%d",i) gets executed first and prints 43 and the function printf returns 2
and similarly other 2 printf's print 2 1


I thought the following C program is perfectly valid (after reading about
the comma operator in C).
But there is a mistake in the following program, can you identify it?

#include 

int main()
{
int a = 1,2;
printf("a : %d\n",a);
return 0;
}

Solution:

error in the line int a = 1,2;

Here the declaration and definition is happening at the same time and hence compiler
associates/initializes a to 1 but for 2 it considers as variable and since it
is a not a valid variable(variable names cannot start with digits) it throws
out an error.




No comments:

Post a Comment