Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this undefined behaviour in C++?

I was wondering whether the access to x in the last if below here is undefined behaviour or not:

int f(int *x)
{
    *x = 1;
    return 1;
}

int x = 0;
if (f(&x) && x == 1) {
    // something
}
like image 949
Andrea Bergia Avatar asked Nov 27 '22 18:11

Andrea Bergia


2 Answers

It's not undefined behavior as operator && is a sequence point

like image 138
Dani Avatar answered Nov 30 '22 08:11

Dani


It is well defined.

Reference - C++03 Standard:

Section 5: Expressions, Para 4:

except where noted [e.g. special rules for && and ||], the order of evaluation of operands of individual operators and subexpressions of individual expressions, and the order in which side effects take place, is Unspecified.

While in,

Section 1.9.18

In the evaluation of the following expressions

a && b
a || b
a ? b : c
a , b

using the built-in meaning of the operators in these expressions, there is a sequence point after the evaluation of the first expression (12).

like image 41
Alok Save Avatar answered Nov 30 '22 08:11

Alok Save