C Programming Reference
 
C Programming Reference >> C  Programming Reference Question Bank >>

19/07/07 - 425 Views - Ratings :   4 of 5 / 1 Votes

Level - Begineer
      

Question -

What will be  the output of the following code and why?
#include <stdio.h>
int main()
{
int x = 40; { int x = 20; printf ("%d ", x); } printf ("\n\n%d",x);
}
Answer -
 20


 40
Explanation -

Reason for such a output lies in the fact that in C in a name conflict, in which two identifier have same name, the identifier which is more local gets the greater priority because of which it hides the larger scope variable of same name.

So in the above code more local x ie. second one of the lower scope hides the first local variable x. As a result value output is 20 instead of 40.

Now when the execution reaches outside the inner code block the innermost 'x' gets destroyed and outer 'x' gains dominance and this time when we print the value the outer 'x' value 40 gets displayed because inner 'x' value 40 is destroyed.

Reader Comments -

Author Comments
Add Comments 


Name :    
Reply :   


Rating :

Code :
Code

 

 
© 2006 cencyclopedia.com