三元表达式语句不起作用 [英] C ternary expression-statement not working

查看:163
本文介绍了三元表达式语句不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

为什么 g 无法打印?编译器说需要 lvalue 。是什么意思?

Why does the value of g not get printed? And compiler says lvalue required. What does it mean?

推荐答案

由于运算符的优先级更高?: = 上,表达式

Due to higher precedence of operator ?: over =, the expression

a > b ? g = a : g = b;   

将被解析为

(a > b ? g = a : g) = b;  

表达式(a> b?g = a:g)将给出一个右值。赋值操作符( = )的左操作数必须是左值 1 (可修改的 2 )。

The expression (a > b ? g = a : g) will give an rvalue. The left operand of assignment (=) operator must be an lvalue1 (modifiable2).

更改

a > b ? g = a : g = b ;  

a > b ? (g = a) : (g = b);    

g = a > b ? a : b;






1 。 C11-§6.5.16/ 2:赋值运算符的左操作数应具有可修改的左值。

2 。 §6.3.2.1/ 1: 左值是一个表达式(对象类型不是void)可能指定一个对象 64)如果左值在评估时未指定对象,则该行为未定义。当说一个对象具有特定类型时,该类型由用于指定该对象的左值指定。 可修改的左值是不具有数组类型,不完整的类型,不具有const限定类型的左值,并且如果是结构或联合,则不具有任何成员(包括递归) ,所有包含的集合或联合的任何成员或元素),其类型为const限定类型。


1. C11-§6.5.16/2: An assignment operator shall have a modifiable lvalue as its left operand.
2. §6.3.2.1/1: An lvalue is an expression (with an object type other than void) that potentially designates an object;64) if an lvalue does not designate an object when it is evaluated, the behavior is undefined. When an object is said to have a particular type, the type is specified by the lvalue used to designate the object. A modifiable lvalue is an lvalue that does not have array type, does not have an incomplete type, does not have a const- qualified type, and if it is a structure or union, does not have any member (including, recursively, any member or element of all contained aggregates or unions) with a const- qualified type.

这篇关于三元表达式语句不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆