Is one side of the assignment ordered to the other in C ++?

I understand that this behavior is undefined:

int i = 0; int a[4]; a[i] = i++; //<--- UB here 

since the evaluation order of i for the left and right sides is undefined ( ; is the only point in the sequence).

Taking this argument further, it seems to me that it will be undefined undefined behavior:

 int i = 0; int foo(){ return i++; } int main(){ int a[4]; a[i] = foo(); return 0; } 

Despite the fact that on the right side of = there are several points in the sequence, as I understand it, there are still undefined it is not indicated whether f() or a[i] is evaluated first.

Are my assumptions correct? Should I take painstaking care when I use a global or static variable on the left side of the task, which the right hand does not modify under any circumstances?

+7
c ++ sequence-points
source share
2 answers
 a[i] = foo(); 

It does not indicate whether foo or a[i] will be checked first. In the new C ++ 11 formulation, the two ratings are unaffected. However, this does not cause undefined behavior. This is when there are two disjoint accesses to the same scalar object, at least one of which writes where it works. That is why a[i] = i++; - UB.

The difference between the two statements is that the call to foo() introduces a point in the sequence. C ++ 11 is different: execution inside the called function is vaguely ordered relative to other evaluations inside the calling function.

This means partial ordering between a[i] and i++ inside foo . As a result, either a[0] or a[1] will be set to 0, but the program will be detected correctly.

+6
source share
 a[i] = i++; 

This behavior is undefined because the value of i changed and available between two points in the sequence (and access is not directly involved in calculating the next value of i ). This is also unspecified behavior because the order of evaulation is not specified (increment i can occur before or after using i as an index in a ).

When you enter a function call, for example:

 a[i] = foo(); 

A function call introduces two additional points in the sequence: one before entering the function and one after returning the function.

This means that the increment i inside the function is surrounded by two points in the sequence and does not cause undefined behavior.

This is still unspecified behavior, although whether the function will be called before using i as an index on the left side of the task or after.

+1
source share

All Articles