This behavior is undefined in C / C ++

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

Will it refer to undefined behavior in C / C ++? I think no.

Having read all the answers, I cannot understand if this behavior is undefined or undefined behavior.

+4
source share
5 answers

Yes, this behavior is undefined - a and foo(--a) can be evaluated in any order.

For more information, see, for example, Sequence Point . There is a sequence point after the full expression and after evaluating the foo argument - but the order of evaluating the subexpressions is not specified, at 5/4:

Unless noted, the order of evaluation of the operands of individual operators and subexpressions are separate expressions and the order in which side effects occur is undefined. Between the previous and the next point in the sequence - the scalar object must have a stored value no more than once the evaluation of the expression. In addition, the previous value should only be accessed to determine the value to be stored. The requirements of this clause must be followed for each valid order of subexpression of the full expression; otherwise, the behavior is undefined.

EDIT: As Prasun points out, the behavior is unspecified due to the evaluation order ... not specified. and becomes undefined due to the previous value being reached only to determine the value that needs to be saved

+16
source

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

+5
source

Even if the operands of the + operator can be evaluated in any order, the behavior is undefined because it violates the 2nd rule

1) Between the previous and next points in the sequence, the object must have an unchanged value of the stored value no more than once by evaluating the expression.

2) In addition, the previous value should be consulted only to determine the value to be stored .

The following is well defined.

 c = foo(a-1) + a ; 

Read this FAQ entry for a better understanding of undefined behavior and sequence points.

+3
source

According to Wikipedia + not a sequence point, so the order of evaluation is not fixed, so you have undefined.

+2
source

You will receive a warning for the return type in the main function, otherwise it will be ok and c = 8 at the end of main ().

-1
source

Source: https://habr.com/ru/post/1344750/


All Articles