lvalue required as left operand of assignment in conditional operator [duplicate]

天大地大妈咪最大 提交于 2019-12-14 00:12:53

问题


#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.



来源:https://stackoverflow.com/questions/18312565/lvalue-required-as-left-operand-of-assignment-in-conditional-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!