Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Order of Declaration (in Multi-variable Declaration Line)

I use the following in my C++ code:

int a = 0, b = a;

I would like to know if this behaviour is reliable and well defined (left to right order of name declaration) and that my code will not break with other compilers with an undeclared name error.

If not reliable, I would break the statement:

int a = 0; 
int b = a;

Thank you.

like image 536
pooya13 Avatar asked Dec 10 '18 00:12

pooya13


People also ask

Can you declare multiple variables in one line C?

Example - Declaring multiple variables in a statementIf your variables are the same type, you can define multiple variables in one declaration statement. For example: int age, reach; In this example, two variables called age and reach would be defined as integers.

How do you define multiple variables in one line?

When assigning multiple variables in a single line, different variable names are provided to the left of the assignment operator separated by a comma. The same goes for their respective values except they should be to the right of the assignment operator.

What is multiple declaration in C?

E2238 Multiple declaration for 'identifier' (C++)An identifier was improperly declared more than once. This error might be caused by conflicting declarations, such as: int a; double a; A function declared in two different ways. A label repeated in the same function.


1 Answers

I believe the answer is no.

It is subject to core active issue 1342 which says:

It is not clear what, if anything, in the existing specification requires that the initialization of multiple init-declarators within a single declaration be performed in declaration order.

We have non-normative note in [dcl.decl]p3 which says:

...[ Note: 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;

...

but it is non-normative and it does not cover the initialization case at all and as far as I can tell no normative wording says the same thing.

Although the standard does cover the scope of names in [basic.scope.pdecl]p1 which says:

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

unsigned char x = 12;
{ unsigned char x = x; }

Here the second x is initialized with its own (indeterminate) value. — end example  ]

like image 173
Shafik Yaghmour Avatar answered Nov 15 '22 17:11

Shafik Yaghmour