Vladok AC Vladok AC - 9 days ago 7
C Question

How to Reduce the expression

How to reduce the expression? If I am right, x assign 0 if only x = 0; otherwise x assign 1. However, How can it do shorten?

x = (x = 0) ? 0 : 1

Answer

Keeping aside all the assumption part, first let me state this celarly, there is no undefined behaviour here.

Quoting C11, chapter §6.5.15, Conditional operator (emphasis mine)

The first operand is evaluated; there is a sequence point between its evaluation and the evaluation of the second or third operand (whichever is evaluated). The second operand is evaluated only if the first compares unequal to 0; the third operand is evaluated only if the first compares equal to 0; the result is the value of the second or third operand (whichever is evaluated), [....]

and then, the result is assigned to the LHS of the outer assignment operator.

the statement,

x = (x = 0) ? 0 : 1;

is equivalent to

x = 1;

as x= 0 finally evaluates to FALSE unconditionally.

Related, quoting the standard, chapter §6.5.16, Assignment operators, (emphasis mine)

An assignment operator stores a value in the object designated by the left operand. An assignment expression has the value of the left operand after the assignment,


Note:

that said, related to the understanding mentioned in the question

x assign 0 if only x = 0; otherwise x assign 1

is wrong. There is no if..else..then category condition check present in the given statement.