mandeep
mandeep

Reputation: 283

Why the mentioned code is undefined behaviour in C

The statement a[i]=i++; is undefined as there is a confusion that which value of i(old or new) to use to evaluate the left side to get the L-value. This compiler gives a warning (operation .. may be undefined) for this statement if compiled with -Wall.

In the code below , in the statement x->a = x->b, ++x++->b;
x is being changed and in the left side it is used to get the L-value. For this statement, compiler does not give any warning if executed with -Wall.

Could someone please explain why this is not undefined behaviour? Thanks!

struct Data {
int a;
int b;
} y[4] = { 10, 20, 30, 40};

struct Data *x = y;
int i;

for(i=0; i<2; i++) {
    x->a = x->b, ++x++->b;
    printf("%d %d\t", y[i].a, y[i].b);
}

Upvotes: 3

Views: 129

Answers (2)

Daniel Fischer
Daniel Fischer

Reputation: 183968

The comma operator has the lowest precedence,

expression:
assignment-expression
expression , assignment-expression

so

x->a = x->b, ++x++->b;

is actually

(x->a = x->b), ++(x++->b);

and the comma operator is a sequence point, thus the two modifications to x are sequenced, and there is no undefined behaviour.

Upvotes: 12

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215447

x->a = x->b, ++x++->b; does not invoke undefined behavior. The comma operator has lower precedence than the assignment operator, so this code is equivalent to:

x->a = x->b;
++x++->b;

In the second line there, the postfix ++ operator is modifying x, and the prefix ++ operator is modifying the member b of the dereferenced structure. No sequence point rules are being violated.

Upvotes: 7

Related Questions