Question:What will be output when you will execute following c code?#include<stdio.h>
void main(){
char c=256;
char *ptr="Leon";
if(c==0)
while(!c)
if(*ptr++)
printf("%+u",c);
else
break;
}
Choose all that apply:
A +256+256+256+256
B 0000
C +0+0+0+0
D It will print +256 at infinite times
E Compilation error
+ ExplanationIn the above program c is signed (default) char variable. Range of signed char variable in Turbo c is from -128 to 127. But we are assigning 256 which is beyond the range of variable c. Hence variable c will store corresponding cyclic value according to following diagram:
Since 256 is positive number move from zero in clock wise direction. You will get final value of c is zero.
if(c==0)
It is true since value of c is zero.
Negation operator i.e. ! is always return either zero or one according to following rule:
!0 = 1
!(Non-zero number) = 0
So,
!c = !0 =1
As we know in c zero represents false and any non-zero number represents true. So
while(!c) i.e. while(1) is always true.
In the above program prt is character pointer. It is pointing to first character of string “Leon” according to following diagram:
In the above figure value in circle represents ASCII value of corresponding character.
Initially *ptr means ‘L’. So *ptr will return ASCII value of character constant ‘L’ i.e. 76
if(*ptr++) is equivalent to : if(‘L’) is equivalent to: if(76) . It is true so in first iteration it will print +0. Due to ++ operation in second iteration ptr will point to character constant ‘e’ and so on. When ptr will point ‘ ’ i.e. null character .It will return its ASCII value i.e. 0. So if(0) is false. Hence else part will execute.