取消注释std :: cout语句会产生不同的结果

Hox*_*eni 2 c++

这是程序:

#include <iostream>
using namespace std;


int removeDuplicates(int* nums, int numsSize) {
    int count=1;
    if(numsSize==1)
        return 1;
    else if(numsSize==0)
        return 0;
    for(int i=1;i<numsSize;i++)
    {
        while(i<numsSize && nums[i]==nums[i-1])
        {
            i++;
        }
        if(i==numsSize)
        {
            return count;
        }
        nums[count]=nums[i];
      //  cout << nums[i] << "-"<<std::endl;
        count++;
    }
}
int main() {
    // your code goes here
    int nums[3]={1,1,2};
    cout <<"ans "<< removeDuplicates(nums,3);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

请注意评论

//  cout << nums[i] << "-"<<std::endl;
Run Code Online (Sandbox Code Playgroud)

在函数removeDuplicates中.在当前状态下,函数返回

3

.在取消注释上述陈述时,它会返回

134520320

至少在ideone上这样做:https://ideone.com/5m8xPj

我看到函数末尾应该有一个return语句.为什么编译器在最后没有看到return语句时会返回错误?为什么评论/取消注释导致返回如此奇怪的结果?

谢谢.

Reu*_*nen 5

为什么评论/取消注释会导致返回奇怪的结果.

不返回任何内容会给你未定义的行为:

6.6.3  The return statement                              [stmt.return]

...

Flowing off the end of a function is equivalent to a return with no value;
this results in undefined behavior in a value-returning function.
Run Code Online (Sandbox Code Playgroud)