Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary operator and Sequence Points in C

I've an expression of the form shown below :-

while (count)
{
...
...

    index = ((count == 20)? 0 : index++);
...
...
}

Now Ternary operators are sequence points in C but I believe that the sequence point ends at the test part.

Is this understanding correct and as such will this statement lead to undefined behaviour ?

like image 236
Zshn Avatar asked Jun 12 '12 11:06

Zshn


People also ask

What are the sequence points in C?

The C language defines the following sequence points: Left operand of the logical-AND operator (&&). The left operand of the logical-AND operator is completely evaluated and all side effects complete before continuing. If the left operand evaluates to false (0), the other operand is not evaluated.

What is sequence point operation?

A sequence point defines any point in a computer program's execution at which it is guaranteed that all side effects of previous evaluations will have been performed, and no side effects from subsequent evaluations have yet been performed.

Which is called ternary operator 1 point?

In computer programming, ?: is a ternary operator that is part of the syntax for basic conditional expressions in several programming languages. It is commonly referred to as the conditional operator, inline if (iif), or ternary if.


1 Answers

Right. There's a sequence point after the evaluation of the condition, but the next sequence point is the semicolon terminating the statement. So whenever count != 20, you have the undefined behaviour

index = index++;

since index is modified twice without intervening sequence point.

like image 137
Daniel Fischer Avatar answered Oct 06 '22 03:10

Daniel Fischer