With a conditional ?: expression, at what point do postfix operations occur?

For example, the difference between these two statements:

if ( ucNum++ >= 3 ) // ucNum incremented after comparing its value to 3, correct? { ucNum = 0; } 

vs.

 ucNum++ >= 3 ? ucNum = 0 : 1; // does incrementing it happen somewhere in the middle of the inline? 

It may be specific to the compiler. Where should this occur in conventional terms?

+4
source share
3 answers

The rules are that the condition is evaluated before choosing which alternative to evaluate. Since the evaluation part is ++ , the increment will occur before the assignment (if assignment occurs at all).

Like @caf's comment, there is a sequence point after the control expression. Thus, although (as David Thornley points out) the order of expression evaluations can be rearranged by the compiler (in particular, estimates of side effects), rearrangement cannot intersect points in a sequence.

+7
source

Ok, I tested this in practice (the good thing printf returns int):

 int ucNum = 4; ucNum++ >= 3 ? printf("%d", ucNum) : 1; 

Since the condition is true, it goes to printf, which prints 5. Thus, definitely ucNum increases between evaluating the condition and choosing the return value.

+1
source

You are looking for 6.5.15 / 4 in the C standard. The first expression is fully evaluated, including side effects, before choosing one of the other two. This does not depend on the compiler, except that some compilers can be broken.

+1
source

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


All Articles