此函数如何在不应该返回值时返回值?

How does this function return a value when it shouldn't?

本文关键字:返回值 不应该 函数      更新时间:2023-10-16

这个函数返回一个不应该返回的值。

#include<iostream>
using namespace std;
int foo(int a,int b)
{
    if(a>b)
        return a;
    else if(a<b)
        return b;
}
int main()
{
    int x=7,y=7;
    cout<<foo(x,y);
    return 0;
}

输出为:

7

而且它只在GCC编译器上产生正确的输出(我使用Dev c++)。Turbo C产生了垃圾值。有人能解释一下这是怎么发生的吗?

在所有程序控制路径上不返回值的行为为undefined

编译器可以做任何事情。

你的编译器没有警告你吗?