不再为生存而代码

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

先看这一段代码:

/*
P125
清单7.15  使用迭代求第N个Fibonacci数
*/
#include <iostream>
int fib(int position);
int main(){
    using namespace std;
    int answer,position;
    cout << "Which position? ";
    cin >> position;
    cout << "\n";
    answer = fib(position);
    cout << answer << "th is the " << position << " Fibonacci number.\n";
    cin >> position;
    return 0;
}

int fib(int position){
    if(position < 3) return 1;
    int last  = 1;
    int result = 0;
    int tmp = 0;
    for(int b = 1;b<=position;b++){
        if(b < 3) last = 1;
            result = last + result;
            tmp = result;
            result = last;
            last = tmp;
    }
    //return result;
}

按照一贯的思维肯定认为fib函数里不该注掉返回值的那一行,但你有没有想过,这在VC++6.0 和VS2008 里的VC++都能编译通的过?明天用 VS2013测试一下看看是不是也可以通的过。可能没有人试过吧.今天也是无意中发现的,注掉后不仅能编译通的过,还有返回值,只是返回值不是正确的。虽然我不能断定这是VC++的BUG,但这样的做法会不会产生意想不到的BUG?

在百度搜了一下,发现这篇知道 原来会返回随机值,我就不明白了,既然你返回的也是错误的随机值,为何就不能强制编译通不过呢?这是不是C++留的一个坑?有知道的大神能给个回复不

posted on 2015-06-04 22:12  贤勇  阅读(2560)  评论(0编辑  收藏  举报