Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is (a = 0, a) + (a =1, a) undefined behaviour for int a?

Is

int main()
{
    int a;
    int b = (a = 0, a) + (a = 1, a);
}

defined? Without the , a in each term, the program behaviour is clearly undefined due to multiple unsequenced writes to a, but don't the , introduce adequate sequencing points?

like image 990
Bathsheba Avatar asked May 20 '21 11:05

Bathsheba


1 Answers

No it isn't well-defined. Suppose we replace all sequence point in your code with pseudo code "SQ":

SQ
int b = (a = 0 SQ a) + (a = 1 SQ a) SQ

Then we have SQ a) + (a = 1 SQ where two accesses and one side effect happens to a between sequence points, so it is still undefined behavior.

We could write well-defined (but of course very bad and fishy) code like this:

(0, a = 0) + (0, a = 1)

The order of evaluation of the + operands is still unspecified, but the compiler must evaluate either parenthesis before moving on to the next. So there's always a comma operator sequence point between the side-effects/access of a.

like image 187
Lundin Avatar answered Oct 09 '22 17:10

Lundin