C++教材有这样一道课后练习,通过观察两个人逐年的年龄变化让读者理解i++与++i的区别。练习题源代码如下:
#include<iostream>
using namespace std;
int main()
{
int myAge=39;
int yourAge=39;
cout<<"I am: "<<myAge<<"years old."<<endl;
cout<<"You are: "<<yourAge<<"years old."<<endl;
myAge++;
++yourAge;
cout<<"One year passes..."<<endl;
cout<<"I am: "<<myAge<<"years old."<<endl;
cout<<"You are: "<<yourAge<<"years old."<<endl;
myAge++;
++yourAge;
cout<<"Another year passes..."<<endl;
cout<<"I am: "<<myAge++<<"years old."<<endl;
cout<<"You are: "<<++yourAge<<"years old."<<endl;
cout<<"Let's print it again."<<endl;
cout<<"I am: "<<myAge<<"years old."<<endl;
cout<<"You are: "<<yourAge<<"years old."<<endl;
return 0;
}
如果是我自己手动算,最终的结果是如下:
I am: 39years old.
You are: 39years old.
One year passes...
I am: 40years old.
You are: 40years old.
Another year passes..
I am: 40years old.
You are: 41years old.
Let's print it again.
I am: 41years old.
You are: 41years old.
但是用dev编译器得到的运行结果如下:
I am: 39years old.
You are: 39years old.
One year passes...
I am: 40years old.
You are: 40years old.
Another year passes..
I am: 41years old.
You are: 42years old.
Let's print it again.
I am: 42years old.
You are: 42years old.
教材中有两句话是这样说的:
int i=1;
cout<<i++; //首先使i自增为2,然后输出i自增前的值1
cout<<++i; //首先使i自增为2,然后输出i的当前值2
请问是哪里出问题了呢?编译器会不会出错?(之前学C的时候就听说过不同编译器对自增自减这类运算有不同的运行结果)答案应该是什么样的呢?