Reputation: 51
I am a novice in C and having the following problem while compiling a simple code:
#include <stdio.h>
int main()
{
int i, a, b;
i = 3;
a = b = 0;
printf("Before: ");
printf("%d %d\n", a, b);
i == 3 ? a = 4 : a = 10; /* Line 9 */
printf("After: ");
printf("%d %d\n", a, b);
return 0;
}
Gives me error:
#gcc some.c
In function ‘main’:
some.c:9: error: lvalue required as left operand of assignment
I cannot understand it. What am i doing wrong?
Upvotes: 3
Views: 761
Reputation:
The ternary operator does not work like this. You should use parenthesis to give higher priority to the equality operator. Check the priority precedence. By default, equality operators have least priority.
Upvotes: 0
Reputation: 368
?: is a ternary operator.
ternary operator have higher precedence than '=' operator.
so 9th line of your code work like this..
(i == 3 ? a = 4 : a) = 10;
you have to use parenthesis or modify your sentence.
you can replace your 9th line with either of following line..
i == 3 ? a = 4 : (a = 10);
a = i == 3 ? 4 : 10;
Upvotes: 2
Reputation: 11237
You need to assign outside the ternary operator, not inside of it, because the ternary operator binds tighter than assignment. So you should write
a = ((i == 3) ? 4 : 10);
What you wrote is equal to
(i == 3 ? a = 4 : a ) = 10;
In this code, an rvalue is being assigned to. This is the same error as writing
myfunc() = 16;
Cosmetic note: In this case it is better to use an if else statement instead of a conditional operator, because it is more clear here.
if (i == 3)
a = 4;
else
a = 10;
Upvotes: 2
Reputation: 310950
This operator
i==3 ? a=4 : a = 10;
is equivalent to
( i==3 ? a=4 : a ) = 10;
Use instead
i==3 ? a=4 : ( a = 10 );
Upvotes: 7