【问题标题】:lvalue required as left operand of assignment error in c左值需要作为 c 中赋值错误的左操作数
【发布时间】:2020-10-04 16:06:15
【问题描述】:

我必须编写一个比较 3 个整数的程序。我不明白为什么我不能将变量 a 分配给 min 或 max 变量。

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int a, b, c, max, notmax;
    printf("enter first integer\n");
    scanf("%d", &a);
    printf("enter second integer\n");
    scanf("%d", &b);
    printf("enter third integer\n");
    scanf("%d", &c);
    a > b ? a = max : a = notmax ;
return 0;
}

【问题讨论】:

  • 请提供完整的错误输出。

标签: c lvalue


【解决方案1】:

查看优先级和关联性可能有助于您了解此处发生的情况。赋值的优先级低于 ?: 运算符。 所以声明

a > b ? a = max : a = notmax ; 

被视为:

((a &gt; b ? a = max : a) = notmax );

但是一旦你在适当的地方使用括号,如下所示,一切正常:

a > b ? a = max : (a = notmax) ;

或者甚至可能是这样的:

(a > b ? (a = max) : (a = notmax)) ;

这应该按照您想要的方式强制优先级。使用方括号将有助于评估复合语句。

【讨论】:

    【解决方案2】:

    接受的答案解释说,您看到的错误是由于?:= 之间的运算符优先级造成的。它没有提到什么是最好的解决方法。

    ?: 运算符的计算结果是第二部分的值或第三部分的值。所以它可以用来选择maxnotmax并将其分配给a

    a = a > b ? max : notmax;
    

    但是,你的代码还是有问题,因为maxnotmax还没有被初始化,所以它们的值是indeterminate,读取它们会导致@ 987654321@。在运行此状态之前,您需要确保已为这两个变量赋值。

    【讨论】:

      猜你喜欢
      • 2017-01-10
      • 2011-12-20
      • 2011-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多