现在的位置: 首页 > 综合 > 正文

++i在C、C++中是不是左值?

2013年10月10日 ⁄ 综合 ⁄ 共 1043字 ⁄ 字号 评论关闭

前些天写blog左值与右值(C++学习)时,已经确认在C++中,++i
是左值。可是,今天在newsmth的C语言版上看到一个相关的问题。发现在C语言中,++i不是左值。

例子

一个很简单的例子:

int main()
{
    int i = 0;
    ++i = 5;
    return 0;
}

保存成 hello.c ,分别用 gcc、clang、cl、cc编译

  • gcc 4.5

hello.c: In function ‘main’:
hello.c:4:5: error: lvalue required as left operand of assignment

  • clang 2.8

hello.c:4:9: error: expression is not assignable
    ++a = 5;
    ~~~ ^
1 error generated.

  • cl (visual studio 2010)

用于 80x86 的 Microsoft (R) 32 位 C/C++ 优化编译器 16.00.30319.01 版
版权所有(C) Microsoft Corporation。保留所有权利。

hello.c
hello.c(4) : error C2106: “=”: 左操作数必须为左值

  • cc (sun studio 11)

"hello.c", line 4: left operand must be modifiable lvalue: op "="
cc: acomp failed for hello.c

如果将文件保存为 hello.cpp,分别用 g++、clang、cl、CC编译。却则没有任何错误。

C++标准

++i 在C++中是左值,对此 C++标准(5.3.2)中有明文规定

  • The operand of prefix ++ is modified by adding 1, or set to true if it is bool (this use is deprecated). The operand shall be a modifiable lvalue. The type of the operand shall be an arithmetic type or a pointer to a completely-defined
    object type. The result is the updated operand; it is an lvalue, and it is a bit-field if the operand is a bit-field. If x is not of type bool, the expression ++x is equivalent to x+=1

C 标准

这个,翻了下C99和C1x,没发现明确的条文。

或者我错过了什么重要的东西?抑或犯了很低级的错误? ......

抱歉!评论已关闭.