1

Possible Duplicate:
Error: lvalue required in this simple C code? (Ternary with assignment?)

In the following piece of code I got an error like "lvalue required as left operand of assignment". I am unable to understand why such an error is being reported. But when I am using parenthesis in the expression like (i>j)?(k=i):(k=j) it is not reporting an error. please explain.

int main() {
    int i = 2;
    int j = 9;
    int k;

    (i > j) ? k = i : k = j;
    printf("%d\n", k);

    return 0;
}
AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
fuzzy
  • 229
  • 1
  • 4
  • 15
  • Have a look at Nawaz's answer in: http://stackoverflow.com/questions/6966299/error-lvalue-required-in-this-simple-c-code-ternary-with-assignment – phoxis Aug 22 '12 at 10:43

4 Answers4

3

Without your extra ()s, I think the operator precedence is grouping it as

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

Which obviously isn't what you want and does have lvalue issues.

Fix it with

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

AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
walrii
  • 3,472
  • 2
  • 28
  • 47
2

It's clear that this condition can be rewritten in a better way, but your problem is observed because of the precedence of = and ?: operators.

The assignment operator ?: has higher precedence than =, thus the expression

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

Is equivalent to

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

Which is not correct, because you cannot assign to an expression result.

In fact, this case is similar to (( i > j ) : i : j) = 10; which isn't correct either.

Maksim Skurydzin
  • 10,301
  • 8
  • 40
  • 53
1

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;
 }
AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
swemon
  • 5,840
  • 4
  • 32
  • 54
0

Rather :

k = i > j ? i : j;
Stephane Rouberol
  • 4,286
  • 19
  • 18