c - 在 C 中评估赋值运算符的左操作数有什么意义?

标签 c assignment-operator evaluation

根据 ISO C11 - 6.5.16.3,它表示

  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.

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

int x = 10;
x = 5 + 10;
  1. 左操作数 x 的计算结果为 10,右操作数的计算结果为 15。
  2. 右操作数的值存储在左操作数x指定的对象中。

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

最佳答案

x 被评估为 lvalue 时,它不会评估为 10。它评估为 lvalue 其中 RHS 的值可以存储。如果 LHS 的计算结果不是 lvalue,则该语句将出错。

来自 C99 标准 (6.3.2.1/1):

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.

当您有一个简单的变量时,将 LHS 计算为左值 是微不足道的,例如

 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 求值为 lvalue,它指定数组的第 7 个元素。

关于c - 在 C 中评估赋值运算符的左操作数有什么意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39051512/

相关文章:

C++:为我的类型定义了我自己的赋值运算符,现在 .sort() 不会对我的类型的 vector 起作用?

algorithm - 使用字符串匹配算法或动态规划对齐音符

haskell - 为什么在 Haskell 中正确折叠时打印会影响顺序?

c - 访问pcap文件头

c - 在C中显示特殊字符

.net - 为什么 .NET CLI 不为引用类提供合成的复制构造函数和赋值运算符?

c++ - 分配不同类别的对象时,分配未给出预期结果

c - 在 8051 芯片的 C 中使用 float with 的问题

c++ - 函数指针的意义何在?

r - 如何使用 ggplot2 在表达式中进行替换?