lvalue required as left operand of assignment in c

2019-10-20 20:28发布

问题:

This question already has an answer here:

  • Error: lvalue required in this simple C code? (Ternary with assignment?) 4 answers
#include <stdio.h>
int main()
{
        int a = 1, b;
        a ? b = 3 : b = 4;
        printf("%d, %d", a, b);
        return 0;
}

[user@localhost programs]$ gcc -Wall vol.c
vol.c: In function ‘main’:
vol.c:5:16: error: lvalue required as left operand of assignment
  a ? b = 3 : b = 4;
                ^

I have given lvalue as b then why gcc is showing error and how to fix it?

回答1:

It has to do with operator sequencing. What the compiler thinks you're doing is

(a ? b = 3 : b) = 4

which obviously is incorrect.

Instead, why not put the b on the left side, and get only the value to assign using the conditional expression, like

b = a ? 3 : 4;


回答2:

Conditional operator (?:) always returns a value on the basis of a certain condition becomes true or false. In other words it can be said that ?: returns always an r-value. And an r-value never be placed on left of an assignment expression. The statement

a ? b = 3 : b = 4;

is interpreted by compiler as

(a ? b = 3 : b) = 4;

similar to equating

3 = 4;

which is wrong.
You are claiming that I have given lvalue as b, which is wrong! b will bind to ?: operator and participate in evaluating r-value by the statement

 a ? b = 3 : b;

and hence you are assigning an r-value (3) to an r-value (4)!
To use b as l-value you can do this by doing

b = a ? 3 : 4;

This answer may also help you to understand the binding of operators to the operand ?:.



回答3:

The following compiles:

#include <stdio.h>
int main()
{
    int a = 1, b;
    a ? ( b = 3 ) : ( b = 4 );
    printf("%d, %d", a, b);
    return 0;
}

I would give you a long story about how failing to explicitly parenthesise your dependencies can cause fatal issues in code. But it's like wearing a seatbelt in a car - a lot of people simply refuse to believe it is worth it until they are in a very messy accident.