有人可以澄清这段代码吗?

标签 c function memory stack

我对 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/

相关文章:

r - 使用 dplyr mutate 将列名传递给函数,而不使用折旧的 mutate_

c++ - 在 C++ 中是否有符合标准的方法来指定字段偏移量?

java - 如何为java进程分配合适的RAM量?

r - 如何处理 Ctree in party 包中的内存问题?

c - 帮助我理解 C 中这个简单的 malloc

c - 为什么这个按位运算符结果为假?

c - 我需要内存屏障吗?

c - 对 `strlwr' 的 undefined reference

c++ - 在 C++ 中使用带参数的 Fortran90 子例程

c++ - 函数参数已在函数声明 C++ 中初始化