C++不确定行为

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

程序是这种

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值