8

I am a bit baffled that I managed to accidentally write code equivalent to this one

int a=a; // there is not a declared before this line

and the compiler happily compiled it - both gcc and clang, which are very standard-conforming and have good diagnostics. (With -Wall, gcc 4.8 warns about uninitialized variable; clang does not).

I thought the RHS of the assignment will be evaluated prior do LHS, hence causing a to be undefined on the RHS. Can I have some simple clarification about why is this syntactically legal?

eudoxos
  • 18,545
  • 10
  • 61
  • 110
  • But didn't you get warning like this _warning C4700: uninitialized local variable 'a' used_ – Digital_Reality Jan 16 '14 at 11:17
  • Although you say "the RHS of the assignment will be evaluated prior do LHS", I think that is ignoring the fact that this is also a inline variable declaration. It is equivalent to `int a; a = a;` which is my guess of what the compiler is actually doing. – devrobf Jan 16 '14 at 11:22
  • I got the warning only with gcc with `-Wall`. – eudoxos Jan 16 '14 at 11:22

2 Answers2

4

It will be a compile-time error if you tell GCC to make it so:

gcc -Winit-self -Werror

Note that sadly this diagnostic is not enabled by most of the usual suspects like -Wall.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • The question is more about if+why this construct is legal in C - I will edit the question a bit to clarify that. – eudoxos Jan 16 '14 at 11:20
  • 1
    It's an uninitialized variable. That's legal in C, and the compiler is not required to issue any diagnostic. But the construct is nonsensical and probably an error, so the compiler is capable of warning about it. – John Zwinck Jan 16 '14 at 11:25
  • 1
    Using an uninitialized automatic object is no longer legal in C if its address has not been taken. Per C 2011 6.3.2.1 2, the behavior is undefined. – Eric Postpischil Jan 16 '14 at 12:40
2

The scope of a name starts right after its complete declaration. Thus, a is already in scope at the time of its initialization.

Stroustrup has the very same example as you noted to demonstrate scoping rules.

See: Stroustrup "The C++ Programming Language, 4th ed.", p.158.

Edit: Oops, didn't notice question was tagged with "C", but still, I think it works for C quite as well

qwm
  • 1,005
  • 8
  • 10