Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of initialization for multiple declarators in a single declaration

Tags:

c

Just looked through C99 and C11 trying to figure out whether they guarantee that multiple declarators in a single declaration are executed in order, from left to right. They do say that each full declarator ends in a sequence point

6.7.5C99 Declarators

6.7.6C11 Declarators

3 A full declarator is a declarator that is not part of another declarator. The end of a full declarator is a sequence point.[...]

but there seems to be nothing that would say that individual initializations are carried out in left-to-right order. Is it really unspecified or am I missing something simple?

int main() {
  int i = 0;
  int a = i++, b = i++;
  // Are values of `a` and `b` specified here?
}

If the order is unspecified, it outlaws the following implementation pattern

int array[N];
for (int *element = array, *element_end = element + N; 
     element != element_end; 
     ++element)
  *element = 0;

which strikes me as rather surprising. (I do realize that I can initialize element_end with array + N instead.)

P.S. C++ specification is not exactly explicit in that regard either. It has a footnote that says that T d1, d2; is equivalent to T d1; T d2;, but these are non-normative. Hence apparently the DR#1342

like image 422
AnT Avatar asked Jan 11 '15 21:01

AnT


2 Answers

I don't know how I missed it, considering that I actually searched the entire document for the word "order", but it is really there

6.8C99 Statements and blocks

3 A block allows a set of declarations and statements to be grouped into one syntactic unit. The initializers of objects that have automatic storage duration, and the variable length array declarators of ordinary identifiers with block scope, are evaluated and the values are stored in the objects (including storing an indeterminate value in objects without an initializer) each time the declaration is reached in the order of execution, as if it were a statement, and within each declaration in the order that declarators appear.

like image 108
AnT Avatar answered Sep 18 '22 18:09

AnT


Is it really unspecified or am I missing something simple?

The order is unspecified. This is because , in

 int a = i++, b = i++;

act as separator, not as an operator. The order of initialization is not guaranteed here.

like image 41
haccks Avatar answered Sep 19 '22 18:09

haccks