Reputation: 1
I'm trying to use conditional expression, ?:
, in C but keep getting the error:
expression must be a modifiable lvalue" and "'=': left operand must be l-value".
What did I do wrong?
#include <stdio.h>
#include <stdlib.h>
#pragma warning (disable : 4996)
void main(void) {
int a = 1;
char x;
a == 1 ? x = 't' : x = 'f';
putchar(x);
system("pause");
}
Upvotes: 0
Views: 37
Reputation: 225437
The condition operator ?:
has higher precedence than the assignment operator =
. So this:
a == 1 ? x = 't' : x = 'f';
Parses as this:
(a == 1 ? x = 't' : x) = 'f';
And the result of the ternary operator is not an lvalue (i.e. it can't appear on the left side of an assignment) so it's invalid.
You can use parenthesis to get the grouping you want:
(a == 1) ? (x = 't') : (x = 'f');
But since you're using this operator to assign a value to x
, the proper way to use it would be:
x = a == 1 ? 't' : 'f';
Upvotes: 2