Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is a[i++] = 3 undefined? [duplicate]

I'm a novice programmer (been learning C on a CS course since September) I've been reading the following two questions in order to try and get my head around sequence points and the undefined behaviours which relate to them.

Why are these constructs (using ++) undefined behavior?

Why is a = i + i++ undefined and not unspecified behaviour

I now understand that

a[i] = i++;

results in an undefined behaviour. I was wondering if

a[i++] = 4;

falls into the same category but I can't find anyone discussing this specific example anywhere.

like image 775
Ben Wainwright Avatar asked Feb 21 '26 14:02

Ben Wainwright


2 Answers

No, the latter is not undefined behavior because you're not modifying and accessing i more than once between two sequence points.

like image 124
Filipe Gonçalves Avatar answered Feb 23 '26 06:02

Filipe Gonçalves


That's fine.

The problem with a[i] = i++; is that the modification in i++ is separate from the read in i in a[i]. The modification could take place before, during or after that read.

Since a[i++] = 4; doesn't read i independently from its modification, you don't have that problem.