gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 16:30:11 27 4
gpt4 key购买 nike

根据 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com