Using parentheses in an expression that includes a triple operator

Possible duplicate:
Error: lvalue required in this simple C code? (Ternar with appointment?)

In the following code snippet, I got an error, for example, " lvalue required as left operand of assignment ". I cannot understand why such an error is being reported. But when I use brackets in an expression like (i>j)?(k=i):(k=j) , it does not report an error. Explain, please.

 int main() { int i = 2; int j = 9; int k; (i>j) ? k=i : k=j; printf("%d\n",k); return 0; } 
+1
source share
5 answers

It is clear that this condition can be rewritten better, but your problem is observed due to the priority of the = and ?: Operators.

The assignment operator ?: Has a higher priority than = , therefore the expression

 ( i > j ) ? k = i : k = j; 

Is equivalent

 (( i > j ) ? k = i : k) = j; 

This is not true because you cannot assign the result of an expression.

Actually this case is similar (( i > j ) : i : j) = 10; which is also incorrect.

+2
source

Without your extra () s, I think operator precedence groups it like

((i>j)?k=i:k)=j;

Which is clearly not what you want, and has problems with lvalue.

Fix it

k= (i>j) ? i : j;

+3
source

How about writing like this.

 int main() { int i,j,k; i=2;j=9; k = (i > j) ? i : j; printf("%d\n",k); return 0; } 
+1
source

Rather:

 k = i > j ? i : j; 
0
source

You need to assign the return value of this statement. The syntax for the ternary operator is as follows.

 result = condition ? first_expression : second_expression; 

what you are missing in the code. Therefore, you can simply place it as shown below.

 int k = (i > j) ? i : j; 
0
source

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


All Articles