Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it valid to initiate the size part of a VLA in the same sequencepoint as the VLA is declared?

In this post, the OP contains code where there is a lot wrong with, but 1 line made me especially curios, since I wasn't able to look anything up, disallowing it. This is the specific line:

int n = 100000, arr[n];

Is the order of declaration and initialization beeing ensured?

So here I would assume it might even happen that n wasn't initialized when arr gets declared, what obvisiously would not be good.

But I wasn't able to find any statement regarding this in the iso/iec 9899 draft at hand neither stating it undefined nor defining it.

So is this as I assume not defined behavior? Or is it?

And either way, what is the rule beeing applyed for that result?5

Edit:

Is that valid for C99, too?

like image 505
dhein Avatar asked Jul 12 '16 11:07

dhein


1 Answers

In short: Your code is correct. It is your premise which is wrong. The two declarations are not "in the same sequence point". (As a sidenote: there cannot be anything in a point, but only between two points, points are dimensionless).

The details:

6.8.2 of the standard shows the grammar of a compound statement which is the basis of every function body:

compound-statement:
    { block-item-listopt }
block-item-list:
    block-item
    block-item-list block-item
block-item:
    declaration
    statement

Relevant here is the block-item. As shown, it can be a statement or a declaration. This implies that a declaration is not a statement. You show a declaration, so the , is not an operator here, but seperates the init-declarators (a declarator optionally with an initialiser, see 6.7 for the grammar). And there is a sequence point right after the declarator (and before the optional initialiser, btw.).

6.7.6p3: A full declarator is a declarator that is not part of another declarator. The end of a full declarator is a sequence point. If, in the nested sequence of declarators in a full declarator, there is a declarator specifying a variable length array type, the type specified by the full declarator is said to be variably modified. Furthermore, any type derived by declarator type derivation from a variably modified type is itself variably modified.

Regarding the "execution order": That is actually left to the implementation. But the standard requires to follow the abstract machine. Sequence points are the fundamental ordering concept.


The question is actually not directly related to VLAs, but declarators in general. Without citing the sections of all previous versions, the behaviour is identical in all version, because otherwise something like int i = 3, k = i; would also not work (it does).

like image 170
too honest for this site Avatar answered Sep 23 '22 13:09

too honest for this site