在C中评估赋值运算符的左操作数有什么意义? [英] What's the point of evaluating left operand of assignment operator in C?

查看:199
本文介绍了在C中评估赋值运算符的左操作数有什么意义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据ISO C11-6.5.16.3,它说

According to ISO C11 - 6.5.16.3, it says that

  1. 赋值运算符将值存储在所指定的对象中 左操作数.赋值表达式的值为左侧 赋值后的操作数,但不是左值.的类型 赋值表达式是左操作数之后的类型 左值转换.更新存储值的副作用 左操作数在对左和右的值计算之后进行排序 正确的操作数.操作数的求值没有顺序.
  1. An assignment operator stores a value in the object designated by the left operand. An assignment expression has the value of the left operand after the assignment, but is not an lvalue. The type of an assignment expression is the type the left operand would have after lvalue conversion. The side effect of updating the stored value of the left operand is sequenced after the value computations of the left and right operands. The evaluations of the operands are unsequenced.

所以我想这意味着,例如,

So I guess this means that, for example,

int x = 10;
x = 5 + 10;

  1. 左操作数x的值为10,右操作数的值为15.
  2. 右操作数值存储在左操作数x指定的对象中.
  1. Left operand x is evaluated to 10 and right operand is evaluated to 15.
  2. Right operand value is stored in the object designated by the left operand x.

但是,如果赋值的目的是存储右操作数的确定值(就像在步骤2中一样),为什么需要对左操作数求值呢?评估左操作数有什么意义?

But if the purpose of the assignment is to store the evalauted value of right operand(just like in step2), why is evaluation of left operand necessary? What's the point of evaluating the left operand?

推荐答案

x评估为lvalue时,其不等于10.它将评估为lvalue,RHS的值可以被存储.如果LHS未评估为lvalue,则该语句将是错误的.

When x is evaluated as an lvalue, it does not evaluate to 10. It evaluates to an lvalue where the value of the RHS can be stored. If the LHS does not evaluate to an lvalue, the statement would be an error.

根据C99标准(6.3.2.1/1):

From the C99 Standard (6.3.2.1/1):

左值是一个可能指定对象的表达式(对象类型不是void).如果左值在评估时未指定对象,则行为未定义.

An lvalue is an expression (with an object type other than void) that potentially designates an object; if an lvalue does not designate an object when it is evaluated, the behavior is undefined.

当您有一个简单变量(例如

The evaluation of the LHS as an lvalue is trivial when you have a simple variable, such as

 x = 10;

但是,它可能更复杂.

 double array[10];
 int getIndex();   // Some function that can return an index based
                   // on other data and logic.

 array[getIndex()+1] = 10.0;

 // This looks like a function call that returns a value.
 // But, it still evaluates to a "storage area".
 int *getIndex2() { return(&array[0]); }
 *getIndex2()=123.45; // array[0]=123.45

如果getIndex()返回5,则LHS评估为指定数组第7个元素的 lvalue .

If getIndex() returns 5, then the LHS evaluates to an lvalue that designates the 7-th element of the array.

这篇关于在C中评估赋值运算符的左操作数有什么意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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