no_rain

C中的side effect 和 sequence point

wiki 中 sequence point 定义:
sequence point in imperative programming defines any point in a computer program's execution at which it is guaranteed that allside effects of previous evaluations will have been performed, and no side effects from subsequent evaluations have yet been performed. They are often mentioned in reference to C and C++, because the result of some expressions can depend on the order of evaluation of their subexpressions. Adding one or more sequence points is one method of ensuring a consistent result, because this restricts the possible orders of evaluation.
简单的说就是在C/C++中有一些执行顺序问题,C/C++定义了一些sequence point,在下一个sequence point 执行之前必须把前一个执行完,但是问题是在一个sequence point 和另一个之间还有一些side effect。由于这些就引出一些有趣的问题。
条件运算符?:、逗号运算符、逻辑与&&、逻辑或||的每一个操作数求值之后是Sequence Point。
问题一:
f(g( ), h( ) );
先执行谁?答:g( ),h( ) 的顺序不确定,它们执行之后才执行f ( );
问题二:
int i = 1;i = i ++;
结果是? 答:undefined,因为我们知道i++ 是先返回再改变i的值的,那么赋值语句右边就有了值了,那么就存在这样的两种情况:1,i先赋值,再++,那么i现在为2;2,先++,然后赋值,注意此时赋值的内容是还没++的值,所以i为1;根据不同的编译器会得出不同的结果的。
问题三:
int a  = 1; a = (++a)+(++a)+(++a);
结果是?答:undefined,这个的问题是,到底是先把每个++执行完之后才进行加法还是先把前两个先加再执行最后一个++?两者的答案分别是9,11。当然还有其他情况。
问题四:
int i = 1int a[10]={0}; a[i++= i;
答:同问题2.
所以我们要坚持的原则是:
在两个Sequence Point之间,同一个变量的值只允许被改变一次





posted on 2011-11-14 15:08 is-programmer 阅读(327) 评论(0)  编辑 收藏 引用 所属分类: C/C++


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


导航

<2024年5月>
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678

统计

常用链接

留言簿

随笔档案

文章分类

文章档案

搜索

最新评论

阅读排行榜

评论排行榜