当我使用条件运算符或没有 return 语句的 if 语句时,函数 return 的正确值

Function returns correct value when i use conditional operator or if statement without return statement

#include<stdio.h>
int fact(int);
int main()
{
    int a, b;
    printf("enter a number : ");
    scanf("%d",&a);
    b=fact(a);
    printf("\n%d",b);
}
int fact(int y )
{
    int d=1;
    for(int i = 1;i<=y;i++)
            d*=i;
    d= d>0 ? d : 0;
}

如果我删除最后一条语句,O/P 就是 a+1。 如果我使用 if 语句或条件运算符,我已经用其他函数和函数 returns 检查了它的正确值。 我想知道为什么会这样。 谢谢。

6.9.1 Function definitions
...
12 If the <strong>}</strong> that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined.

简而言之,您看到的行为纯属偶然。没有充分的理由说明您应该得到那个特定结果或任何其他结果。

Undefined 表示代码有错误,但编译器和运行时环境都不需要以任何特定方式处理它。在您的情况下可能发生的情况是,用于 return 函数值的寄存器也被用于存储 d 的值,但 没有 是真的。如果您更改代码,您可能会得到不同的结果。