左值作为条件运算符中赋值的左操作数

man*_*m-n -4 c c++ gcc compiler-errors conditional-operator

#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;
                ^
Run Code Online (Sandbox Code Playgroud)

我给了左值,b然后为什么gcc显示错误以及如何解决它?

Som*_*ude 8

它与操作员排序有关.编译器认为你正在做的是什么

(a ? b = 3 : b) = 4
Run Code Online (Sandbox Code Playgroud)

这显然是不正确的.

相反,为什么不把它b放在左侧,只得到使用条件表达式赋值的值,比如

b = a ? 3 : 4;
Run Code Online (Sandbox Code Playgroud)