The question title says it all: do declarations of the form int a = 0, b = a
have undefined behavior?
So, in C/C++ programming, undefined behavior means when the program fails to compile, or it may execute incorrectly, either crashes or generates incorrect results, or when it may fortuitously do exactly what the programmer intended.
Undefined Behavior results in unpredicted behavior of the entire program. But in unspecified behavior, the program makes choice at a particular junction and continue as usual like originally function executes.
An infinite loop is well defined behavior. Transferring execution to a function and returning is well defined behavior. The compiler can only determine the behavior of the loop based on the declaration of the function.
When hasChild is false, getChild is to return an undefined value.
No, this is well-defined. This is a declaration with two declarators, a
and b
. Each declarator has an initializer.
Each init-declarator in a declaration is analyzed separately as if it was in a declaration by itself.
That is, the line is treated like:
int a = 0;
int b = a;
No, there is no Undefined Behavior.
Per Paragraph 8/3 of the C++11 Standard:
Each init-declarator in a declaration is analyzed separately as if it was in a declaration by itself
Also, as footnote 97 specifies:
A declaration with several declarators is usually equivalent to the corresponding sequence of declarations each with a single declarator. That is
T D1, D2, ... Dn;
is usually(*) equivalent to
T D1; T D2; ... T Dn;
This means that a
is initialized first, then b
is initialized and assumes the value of a
. Also notice that even if this was not the case, there has been quite a long debate on SO over whether this would or would not be UB, and some consensus has been reached on this not being UB.
(*): As explained by Olaf Dietsche in the comments, the situations where this equivalence does not hold are mentioned later on in the same footnote.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With