Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this undefined behavior in C/C++

int foo(int c){
    return c;
}

int main(void){
    int a=5,c;
    c = foo(--a) + a; 
}

Will it invoke undefined behavior in C/C++? I think no it won't.

After reading all the answers I can't figure out whether it is undefined behavior or unspecified behavior.

like image 342
jaya Avatar asked Nov 28 '22 03:11

jaya


2 Answers

Yes it's undefined behavior - a and foo(--a) can be evaluated in any order.

For further reference, see e.g. Sequence Point. There's a sequence point after the complete expression, and after evaluation of the argument to foo - but the order of evaluation of subexpressions is unspecified, per 5/4:

Except where noted, 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. Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored. The requirements of this paragraph shall be met for each allowable ordering of the subexpressions of a full expression; otherwise the behavior is undefined.

EDIT: As Prasoon points out, the behavior is unspecified due to the order of evaluation ... is unspecified., and becomes undefined due to the prior value shall be accessed only to determine the value to be stored

like image 82
Erik Avatar answered Dec 05 '22 11:12

Erik


You should read this, it will tell you that your code is undefined because + is not a sequence point and as such it is undefined whether f(--a) or a is evaluated first.

like image 24
filmor Avatar answered Dec 05 '22 11:12

filmor