z****e 发帖数: 2024 | 1 #include
using std::cout;
using std::endl;
main(){
int ip[4]={0,1,2,3};
int k=0;
cout<
}
结果:
1 0 1
怎么解释呢?
早谢了。 |
t****t 发帖数: 6806 | 2 it's undefined.
【在 z****e 的大作中提到】 : #include : using std::cout; : using std::endl; : main(){ : int ip[4]={0,1,2,3}; : int k=0; : cout<: } : 结果: : 1 0 1
|
z****e 发帖数: 2024 | 3 为什么呢?不是都合法的代码,而且都很正常的呀,就是结果不理解。
【在 t****t 的大作中提到】 : it's undefined.
|
t****t 发帖数: 6806 | 4 这个跟i++*++i是一样的性质. 合法的代码是什么定义? 不是说编译器不报错就叫合法
代码的.
【在 z****e 的大作中提到】 : 为什么呢?不是都合法的代码,而且都很正常的呀,就是结果不理解。
|
c***k 发帖数: 1589 | 5 恩,你需要看看compiler的书,因为上面这段代码具体的实现是和compiler相关的 |
l**********m 发帖数: 1 | 6 The presence of increment operator changed the execution order. It is
compiler dependent, since standard c++ doesn't define the order explicitly.
Your k++ is evaluated to 0 first, and then it increments k to 1. Then ip[k]
and k are evaluated to ip[1]=1 and 1.
【在 z****e 的大作中提到】 : #include : using std::cout; : using std::endl; : main(){ : int ip[4]={0,1,2,3}; : int k=0; : cout<: } : 结果: : 1 0 1
|
u***i 发帖数: 489 | 7 为啥第一个输出是1呢?
.
]
【在 l**********m 的大作中提到】 : The presence of increment operator changed the execution order. It is : compiler dependent, since standard c++ doesn't define the order explicitly. : Your k++ is evaluated to 0 first, and then it increments k to 1. Then ip[k] : and k are evaluated to ip[1]=1 and 1.
|
X****r 发帖数: 3557 | 8 因为计算ip[k]的时候k为1啊。
前面都说了这种情况是unspecified behavior,因为这个表达式里的
各个部分的计算顺序是没有被规定的。这样的错误代码没有什么可研究的。
记得两点就够了:一是自己不要写;二是看到别人写的搞清楚他要表达什
么意思把它改为正确的。
【在 u***i 的大作中提到】 : 为啥第一个输出是1呢? : : . : ]
|
u***i 发帖数: 489 | 9 多谢指点。。呵呵。。
【在 X****r 的大作中提到】 : 因为计算ip[k]的时候k为1啊。 : 前面都说了这种情况是unspecified behavior,因为这个表达式里的 : 各个部分的计算顺序是没有被规定的。这样的错误代码没有什么可研究的。 : 记得两点就够了:一是自己不要写;二是看到别人写的搞清楚他要表达什 : 么意思把它改为正确的。
|