Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

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?

Perhaps it is compiler specific. Where should it occur in the conditional expression?

like image 633
paIncrease Avatar asked Jan 18 '23 05:01

paIncrease


2 Answers

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

As @caf comments, there is a sequence point after the controlling expression. So, while (as David Thornley points out) the order of expression evaluations can be rearranged by the compiler (particularly side effect evaluations), the rearranging cannot cross sequence points.

like image 50
Ted Hopp Avatar answered Mar 14 '23 02:03

Ted Hopp


Well, I've tested this practically (good thing printf returns int) with:

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

Since the condition is true, it goes to the printf which prints 5. So definitely ucNum is incremented between the evaluation of the condition and the choosing of the return value.

like image 21
Tudor Avatar answered Mar 14 '23 02:03

Tudor