c - 为什么函数调用不是左值

标签 c language-lawyer lvalue function-call

这应该是非常明显的,但我无法在标准中明确指出函数调用是(不是)左值的任何规范性引用。有一些相关question ,但它是关于 C++ 的,没有提供引用。

查看6.5.2.2(p5)函数调用我唯一能找到的是

If the expression that denotes the called function has type pointer to function returning an object type, the function call expression has the same type as that object type, and has the value determined as specified in 6.8.6.4

6.3.2.1(p1) 指出

An lvalue is an expression (with an object type other thanvoid) that potentiallydesignates an object

所以我试图查找函数调用是否指定一个对象。标准中没有规定函数调用结果是否有存储期限和生存期。由于任何对象都有存储持续时间和生命周期,我得出的结论是任何函数调用表达式都不会指定对象,因此不是左值。

但这看起来令人困惑和复杂。特别是我找到了一个示例 6.5.2.3(p7):

EXAMPLE 1 If f is a function returning a structure or union, and x is a member of that structure or union, f().x is a valid postfix expression but is not an lvalue.

根据此示例判断,如果f() 是左值,f().x 也将是左值。但例子信息丰富,让我感到困惑。

最佳答案

它不是左值,因为它在您引用的段落中被描述为“值”。标准明确提到表达式何时具有左值属性。例如:

6.5.3.2 Address and indirection operators (emphasis mine)

4 The unary * operator denotes indirection. If the operand points to a function, the result is a function designator; if it points to an object, the result is an lvalue designating the object. If the operand has type ''pointer to type'', the result has type ''type''. If an invalid value has been assigned to the pointer, the behavior of the unary * operator is undefined.

至于访问 union 或成员(member)。标准不要求 expr.id 中的后缀表达式为左值。相反。整个成员访问与后缀表达式具有相同的值类别:

6.5.2.3 Structure and union members (emphasis mine)

3 A postfix expression followed by the . operator and an identifier designates a member of a structure or union object. The value is that of the named member, and is an lvalue if the first expression is an lvalue. If the first expression has qualified type, the result has the so-qualified version of the type of the designated member.

因此,在您引用的示例中,f().x 是一个值,而不是左值,因为 f() 本身不是左值。

关于c - 为什么函数调用不是左值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55557638/

相关文章:

c++ - 为什么这个initializer_list构造函数是一个可行的重载?

c++ - 不允许从函数返回函数。我怎么能?

c++ - 右值引用被视为左值?

c++ - 错误 : invalid initialization of non-const reference of type ‘bool&’ from an rvalue of type ‘std::vector<bool>::reference {aka std::_Bit_reference}’

c - 如何在 C 中将 int 打印为二进制?

c - 在 ARM Cortex M0 uart 控制台使用 printf() 打印 float

c++ - 一些 STL 容器的 std::allocator 不匹配

C++ 箭头类型产生左值

c - 扫描整数数组

我可以在 C 中使用函数来定义数组的长度吗?