int foo = foo;
compiles.
Which part of the C++ standard allows this?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
The behaviour is well defined if the declaration is at file scope. If you have the declaration at function scope and if you use
foo
later on [which would be initialized to some unspecified value in that case] the behaviour would be undefined.This?
The object
foo
does exist after the=
, according to[basic.scope.pdecl]
:However, the program as a whole is undefined, because you use (on the RHS) an uninitialised value:
And:
Though "inferred and ill-specified" by the standard, an lvalue-to-rvalue conversion is performed on the RHS expression
foo
.And (
[conv.lval]
):With proper warning levels, you will get told about it; however, programs invoking Undefined Behaviour are allowed to compile. They just can do anything at all when you run them.
Or, what about this?
Notice that
foo
is a "global". These are zero-initialised as a first step, according to[basic.start.init]
:So you'll get an
int foo
with value 0; it's valid, at this point, as per[basic.scope.pdecl]
above, and as per[stmt.decl]
:You then value-initialise it to
foo
(itself), i.e. 0.This is well-defined... if a little cryptic.
In the interests of thoroughness, here's a third and final case:
Sadly, this is the same as the first case. Since the local
foo
is already declared and in scope by the time the initializer is evaluated, the initializer uses the localfoo
and you're still stuck with the Undefined Behaviour. The globalfoo
is not used.