#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 语句或条件运算符,该函数将返回正确的值。 我想知道为什么会发生这种情况。 谢谢。
最佳答案
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.
简单地说,您所看到的行为纯粹是偶然的。没有充分的理由说明为什么您应该得到该特定结果或任何其他结果。
未定义意味着代码是错误的,但编译器和运行时环境都不需要以任何特定方式处理它。在您的情况下可能发生的情况是,用于从函数返回值的寄存器也用于存储 d
的值。 ,但这不一定是真的。如果更改代码,可能会得到不同的结果。
关于c - 当我使用条件运算符或不带 return 语句的 if 语句时,函数返回正确的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58647812/