Search code examples
c++standards

Why does C++ allow you to reference a declared variable in the initial definition?


The following program compiles and runs just fine.

#include <iostream>

using namespace std;

int main() {
    size_t foo = sizeof(foo);
    cout << foo << endl;
    return 0;
}

Using the compilation command

clang++ -o wut -Wall -Wextra -Werror -pedantic -ansi test.cc

I understand that this is probably the equivalent of

size_t foo;
foo = sizeof(foo);

Which makes more sense.

However, the initial statement breaks my mind a bit since I think of the RHS being evaluated prior to the LHS (or overall statement) being executed - which in this case might suggest that foo doesn't yet exist.

However, my assumption is that size_t foo always results in a declaration first, being broken out into its own statement during compile-time, followed by the definition.

Is my assumption correct? Is this governed/well defined in the specification(s)? If so, which section(s)? I realize I compiled with -ansi but this appears to work, without error, on all standard versions I tried it with.


Solution

  • You're looking for [basic.scope.pdecl]:

    The point of declaration for a name is immediately after its complete declarator (Clause 11) and before its initializer (if any), except as noted below.

    So once it gets to the =, the definition of foo is complete (which is also a declaration) and it can be referred to in its own initializer.