17

When I'm defining some variables like this:

int a = pop(), b = pop(), c = pop();

does C++ give a guarantee that a is going to be initialized first, then b and then c? or is the order not defined?

5
  • 1
    Could you explain why this is important? We might give a better answer Commented Mar 6, 2013 at 13:29
  • 1
    I want to write just one line instead of 3 lines :) Commented Mar 6, 2013 at 13:34
  • 4
    Improve readability and assert your order by using 3 lines. It's as simple as that. What's the point of getting rid of two lousy lines anyway? Commented Mar 6, 2013 at 13:35
  • I agree with @stefan. I rarely (never?) use multiple declarations in one line. Commented Mar 6, 2013 at 13:46
  • 4
    If this occurs in a for-init-statement such as for (int a = pop(), b = pop(), c = pop(); ...) then the question is more interesting. You could put two of the declarations on the previous line, but now they have a different scope Commented Mar 6, 2013 at 13:47

1 Answer 1

12

[dcl.decl]/3 says

-3- Each init-declarator in a declaration is analyzed separately as if it was in a declaration by itself.

Which means your code is treated like:

int a = pop();
int b = pop();
int c = pop();
Sign up to request clarification or add additional context in comments.

7 Comments

Hmm - I'm not convinced that this implies a predictable order of initialisation...
which still doesn't guarantee any particular order.
Note 97 provides an explanation, but uses the work "usually". I believe, however, that this only means that there are well-defined exceptions to this rule, but it is not "up to the compiler".
@JonathanWakely: so arguably a (minor) defect in the standard, if one has to rely on a footnote for a normative statement of the required behavior. But I think you're correct about what the standard intends to define :-) In such moments I usually say that although footnotes aren't normative, they generally are true.
@JonathanWakely: yes, I've just noticed that. [dcl.init] is exactly the place, and in fact in the note #97 (open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3242.pdf) it is quite clearly stated that the T a,b,c is a "sequence" and is equivalent to T a;T b;T c;. The word "usually" refers not to exception in the comprehension of a sequence, but to the potential collision of identifiers: T a, T, b, c; is surely not equivalent to T a; T T; T b; T c;. Therefore I agree that it is defined, but damn, I'd like it to be written plainly as a proper point, not a footnote..
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.