Auto variables in different blocks in C

void main()
{
int p=100;
clrscr();
printf("\n P=%d",p);
{
int p=50;
printf("\n P=%d",p);
}
{
int p=40;
printf("\n P=%d",p);
}
printf("\n P=%d",p);
}

Output

P=100
P=50
P=40
P=100

In the above program, the declaration of ‘p’ is made at three places with different values. In the first block, the value of ‘p’ is 100 and the same is displayed on the screen first. In the second block, the value of ‘p’ is 50. The control passes to the second block and ‘p’ is assigned a new value 50 and the same is displayed. When the control goes to third block, ‘p’ is 40 and the displayed value is 40. After it exits from the third block, the value of ‘p’ vanishes, which is initialized in the third block. In the last printf() statement, the value of ‘p’ is 100 which is declared in the first block.

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.