首页 > 解决方案 > 左值需要作为 c 中赋值错误的左操作数

问题描述

我必须编写一个比较 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;
}

标签: clvalue

解决方案


查看优先级和关联性可能会帮助您了解这里发生的事情。赋值的优先级低于 ?: 运算符。所以声明

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

被视为:

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

但是一旦您在适当的位置使用括号,如下所示,一切正常:

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

或者甚至可能是这样的:

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

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


推荐阅读