我对 C 的基础知识有疑问。
- 我编写了以下代码。在
add()
函数中,我没有返回任何内容,因此我预计输出将是一些垃圾值或其他内容,但事实并非如此。谁能向我解释为什么会这样?如果代码中有写错的地方,请多多包涵。 - 据我了解,我认为变量
add1
的内存将来自堆栈,因此一旦add()
完成,所有分配的内存都将被释放,因此会显示一些垃圾值。 - 我明显的疑问是,如果不返回任何内容,它如何打印正确的值?
代码示例:
main() {
int x = 4, sum;
int n;
printf(" enter a number \n");
scanf("%d", &n);
sum = add(x, n);
printf(" total sum = %d\n", sum);
}
add(int x, int n) {
int add1 = 0;
add1 = x + n;
//return(add1);
}
最佳答案
这是未定义的行为。
当你不指定函数返回值时,它将默认为 int。那么当你没有 return 语句时,发生的事情将是不确定的。所以原则上任何事情都可能发生。
对于gcc
,它在许多系统上只返回一些“随机”值。就你而言,它恰好是总和。纯粹是靠“运气”。
在编译期间始终打开警告,例如gcc -Wall
并始终将警告视为错误。
您的代码应类似于:
#include <stdio.h>
int add(int x,int n); // Corrected
int main(void) // Corrected
{
int x=4,sum;
int n;
printf(" enter a number \n");
scanf("%d",&n);
sum = add(x,n);
printf(" total sum = %d\n",sum);
return 0; // Corrected
}
int add(int x,int n) // Corrected
{
int add1=0;
add1 = x+n;
return add1; // Removed the // to uncomment and removed unnecessary ()
}
关于有人可以澄清这段代码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38259658/