在VC编程中,你是不是发现一个程序在最优化后,其运行行为就不是你想要的,而在不优化的时候,却表现出是你想要的,神奇吧?OK,带你来看其中一种这种情况:
在VC2005中的一个c++ 返回值为bool类型的函数,该bool类型函数的默认返回值应该true还是false ? 不一定是true也不一定是false , 而是随着编译优化选项而变化。具体进行了如下测试
#include <iostream>
using namespace std;
//测试test函数4种优化情况的返回值结果如下:
//不优化 /od false
//最小体积优化 /o1 true
//最大速度优化 /o2 true
//完全优化 /ox true
bool test(bool b)
{
if (b)
{
return true;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
if (test(false))
{
cout<<"true"<<endl;
}
else
{
cout<<"false"<<endl;
}
return 0;
}
总结:其实并不是编译器的错,而是代码写得不够严格和规范O(∩_∩)O哈哈~
当然,其实只要注意编译器的警告选项就行了:
f:\2013\algorithm\algorithm\algorithm.cpp(106) : warning C4715: 'test' : not all control paths return a value