什么是的+ = C和C ++的结果呢? [英] What's the result of += in C and C++?

查看:123
本文介绍了什么是的+ = C和C ++的结果呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下code:

#include <stdio.h>
int main(int argc, char **argv) {
    int i = 0;
    (i+=10)+=10;
    printf("i = %d\n", i);
    return 0;
}

如果我尝试使用gcc我得到一个错误编译它作为一个C源代码:

If I try to compile it as a C source using gcc I get an error:

error: lvalue required as left operand of assignment

但是,如果我用编译成 C ++ 的g ++ 我没有得到任何错误,当我运行可执行

But if I compile it as a C++ source using g++ I get no error and when i run the executable:

i = 20

为什么不同的行为?

Why the different behaviour?

推荐答案

加载指定运营商的语义是C和C ++不同的:

Semantics of the add-assign operators is different in C and C++:

C99标准,6.5.16,第3部分:

C99 standard, 6.5.16, part 3:

赋值运算符存储在由左操作数所指定的对象的值。一个
  转让前pression有分配后左操作数的值,而不是一个
  左值。

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.

在C ++ 5.17.1:

In C++ 5.17.1:

赋值运算符(=)和复合赋值运算符的所有组从右到左。所有这些都需要能够在作案科幻
  左值作为其左操作数并返回与该类型和分配后的左操作数的值的左值已经发生。

The assignment operator (=) and the compound assignment operators all group right-to-left. All require a modifiable lvalue as their left operand and return an lvalue with the type and value of the left operand after the assignment has taken place.

编辑:的行为(I + = 10)+ = 10用C ++未定义在C ++ 98,但在明确界定C ++ 11。请参见这个答案的问题> NPE 为标准的相关部分。

EDIT : The behavior of (i+=10)+=10 in C++ is undefined in C++98, but well defined in C++11. See this answer to the question by NPE for the relevant portions of the standards.

这篇关于什么是的+ = C和C ++的结果呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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