由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
Programming版 - 一个C++语法问题
相关主题
post incrementquestion about c++ constructor
private destructor[C++] 入门级问题 increment and decrement operators
请问这个C++程序有什么问题吗问一个for循环的问题
two c++ interview questions! (转载)member and friend
namespace defined in another fileOne c++ non-type template question
question for C++ constantg++ default optimization error
C++ 的 问题数组指针的问题
how do I reseat a reference?const char *p, is it ok to change p[1] ?
相关话题的讨论汇总
话题: ip话题: endl话题: cout话题: std话题: c++
进入Programming版参与讨论
1 (共1页)
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,因为这个表达式里的
: 各个部分的计算顺序是没有被规定的。这样的错误代码没有什么可研究的。
: 记得两点就够了:一是自己不要写;二是看到别人写的搞清楚他要表达什
: 么意思把它改为正确的。

1 (共1页)
进入Programming版参与讨论
相关主题
const char *p, is it ok to change p[1] ?namespace defined in another file
一个multithreading 问题question for C++ constant
最初级的白痴C++问题C++ 的 问题
a simple C++ questionhow do I reseat a reference?
post incrementquestion about c++ constructor
private destructor[C++] 入门级问题 increment and decrement operators
请问这个C++程序有什么问题吗问一个for循环的问题
two c++ interview questions! (转载)member and friend
相关话题的讨论汇总
话题: ip话题: endl话题: cout话题: std话题: c++