Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does `int a = 0, b = a` have undefined behavior? [duplicate]

The question title says it all: do declarations of the form int a = 0, b = a have undefined behavior?

like image 443
Paul Manta Avatar asked Mar 12 '13 20:03

Paul Manta


People also ask

What is C++ undefined behaviour?

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.

Is unspecified behavior undefined behavior?

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.

Is an infinite loop undefined behavior?

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.

How do you return undefined in C++?

When hasChild is false, getChild is to return an undefined value.


2 Answers

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;
like image 161
Joseph Mansfield Avatar answered Sep 17 '22 11:09

Joseph Mansfield


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.

like image 20
Andy Prowl Avatar answered Sep 18 '22 11:09

Andy Prowl