I am wondering why the value of register integer a is not overwritten:
#include <stdio.h>
#include <conio.h>
main()
{
register int a=10;
{
register int a=30;
}
printf("%d",a);
getch();
}
Why isn’t the value of a overwritten? The output is showing 10.
Having those braces inside your function creates a new nested block. That means that your line:
is declaring a new variable that also happens to be called
a. If you add another call to printf, you’ll see that happening (I rewrote your program a bit to remove the unnecessaryregisterkeywords and cleaned up some things to make it be standard C, too):The output from this program is:
The inner
a(the one set to30) is said to shadow the other local variable. You can create an arbitrary number of nestings, if you want. For example, this next program:Produces this output:
The redeclarations of
ahide all other declarations ofaoutside the current scope/block. What all of this means is that your original program is semantically equivalent to:Since the inner
awas set but never used. In fact, turning on some warning flags might let the compiler give some diagnostic messages about what’s going on. I usedclanghere: