码迷,mamicode.com
首页 > 编程语言 > 详细

C++不确定行为

时间:2014-10-11 14:25:55      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:c++   编程   

     一个简单的程序引发了一块让人纠结的领域,或许强调编程规范的重要性也在这把,规范了就容易避免一些问题。

程序是这样的

int Change(int& a)
{
   a = 4;
  return a;
}

int main()
{
  int a = 10;
  cout << Change(a) << a;
}

In C-Free : the output : 4 4

In VS2008 : the output : 4 10

区别出来了,按我的理解,应该C-free输出的对,但是还是探究了下,以下是我别人给我的回复:


Simply put, there is no rule that guarantees that "4 4" is right. Same goes for "4 10".

As others have mentioned in the comments you have a case of undefined behaviour here. Even if this would be defined behaviour, code like this is difficult to understand. So I recommend to do

cout << Change(a);
cout << a;

or

int b = a;
cout << Change(a);
cout << b;

whatever you really want to do.

另外,找到了C++不确定行为的一片天,有兴趣的可以在这里继续探究很多C++出现不确定行为的情况。

http://en.cppreference.com/w/cpp/language/eval_order

C++不确定行为

标签:c++   编程   

原文地址:http://blog.csdn.net/u013016027/article/details/39992287

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!