C++ 中关于cout和i++、++i的问题
PHP中文网
PHP中文网 2017-04-17 11:04:20
0
3
722
#include <iostream>
using namespace std;
int main(){
	int i=0;
	cout<<i++<<" "<<i++<<endl;//输出1 0
	i=0;
	cout<<++i<<" "<<++i<<endl;//输出2 2

}

对以上代码的输出如何解释?不太明白(编译环境为VS2010)

PHP中文网
PHP中文网

认证高级PHP讲师

reply all(3)
阿神

I agree with what Blue Skin Mouse said, please stop worrying about things related to compiler details, because firstly, you don’t need to understand, and secondly, if you need to understand, it can only be when you are writing this compiler. Third, no matter how much you know, it may have something to do with the platform, CPU, etc. - they can change at any time. In a word, this is not a recommended coding style, please avoid this way of writing.

I tested with i686-apple-darwin11-llvm-g -4.2 (GCC) 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00) on my Mac, and the results were as you said Same.

The reasons why this might happen are:

cout<<i++<<" "<<i++<<endl;//输出1 0

is equivalent to

operator<<( operator<<( operator<<(cout, i++), " "), i++);

For implementation details in C , see http://en.wikipedia.org/wiki/Sequence...,而上面这个函数表现的和你想的不一样,是因为函数参数的evaluation顺序没有定义,编译器可以做它自己想做的优化,比如就先把外层函数调用的参数i evaluate成0,i变成了1,然后内层调用再得到的就是i==1了。

伊谢尔伦

Don’t worry about this kind of issue that is very related to compiler processing. You will rarely encounter such a scenario in the real world.
Okay, let me say a few more words since I have been stepped on. This kind of stupid scene should only appear in Chinese exams and garbage books published by domestic authors.

Peter_Zhu

I remember once having such a problem, in C language:

#include <stdio.h>
int main()
{
    int a, b;
    a = 2;
    b = (++a) * (++a) * (++a);
    printf("%d\n", b);
    return 0;
}

The output result of gcc is 80, but the result of TC is 60. According to several of us, the reason is that the gcc compiler handles it like this:

    a = ++a;                //a == 3 
    a = ++a;                //a == 4
    b = a * a               //b == 4 * 4==16
    a = ++a;                //a == 5
    b = b * a;              //b == 16 * 5 == 80

The TC compiler handles it like this:

    a = ++a;                //a == 3
    b = 3 * (++a);
    a = ++a;                //a == 4
    b = 3 * 4;
    a = ++a;                //a == 5
    b = b * a;              //b == 12 * 5 == 60

From my personal understanding, C language or C is just a standard. Each compiler has its own implementation method without violating the standard, so when writing code, be careful not to write such ambiguous things. , otherwise the portability will be too poor and various problems will easily occur. In fact, there is no need to delve into it unless it is for research needs.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template