the same id in the same scope refers to different objects
Andrew Makhorin
mao@gnu.org
Sun Sep 3 10:41:00 GMT 2017
On Sun, 2017-09-03 at 16:52 +0800, Xi Ruoyao wrote:
> On 2017-09-03 11:15 +0300, Andrew Makhorin wrote:
> > Hello,
> >
> > Could anyone tell me if the behavior of the following program is
> > correct? Or there is an error not detected by GCC?
> >
> > mao@corvax:~/Desktop$ cat foo.c
> > #include <stdio.h>
> >
> > int x = 111;
> >
> > int main(void)
> > { int y = x + 222;
> > int x = 555;
> > printf("x = %d; y = %d\n", x, y);
> > return 0;
> > }
> > mao@corvax:~/Desktop$ gcc foo.c
> > mao@corvax:~/Desktop$ ./a.out
> > x = 555; y = 333
> > mao@corvax:~/Desktop$ gcc --version
> > gcc (Debian 4.7.2-5) 4.7.2
> >
>
Thank you for your response.
> What the meaning of "correct" is? Of course this program is
> well-formed and the result is standard conforming.
Probably my question is badly formulated, so I reformulate it, because
if the result is "standard conformig", it seems to be inconsistent:
Why x used to initialize y identifies not the same object as x used in
printf though x is the same identifier within the same block scope?
>
> If your "error" means "silly mistake", and you want GCC to help
> you to detect silly mistakes, you should use warnings. For this
> example:
>
> $ gcc-4.7 shadow.c -Wshadow
> shadow.c: In function 'main':
> shadow.c:7:11: warning: declaration of 'x' shadows a global declaration [-Wshadow]
> shadow.c:3:5: warning: shadowed declaration is here [-Wshadow]
More information about the Gcc-help
mailing list