c - 堆和栈段

标签 c for-loop static heap-memory stack-memory

我遇到了一个小谜题,我试图找到它的输出。一旦我设法获得输出,我调整了 1 行,输出就完全不同了。为什么以下两个程序的输出不同?:

一)

#include<stdio.h>
int fun()
{
  static int num = 40;
  return num--;
}

int main()
{
  for(fun(); fun(); fun())
  {
    printf("%d ", fun());
  }
  getchar();
  return 0;
}

输出:

38 35 32 29 26 23 20 17 14 11 8 5 2

二)

#include<stdio.h>
int fun()
{
  static int num;
  num  = 40;
  return num--;
}

int main()
{
  for(fun(); fun(); fun())
  {
    printf("%d ", fun());
  }
  getchar();
  return 0;
}

输出:无限循环每次打印40

只有一个区别:声明和初始化在 (a) 中同时进行,但在 (b) 中分开进行。这对最终结果有何影响?

最佳答案

static int num = 40;

static int num;

这些都被评估一次。 num 不存在于运行时堆栈中(而是存在于数据段中)然后,

num = 40;

每次调用 fun() 时都会进行评估。您将在堆栈外声明的变量重新分配给 40,导致它永远循环。

关于c - 堆和栈段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22052789/

相关文章:

javascript - 如果具有相同属性值的对象已存在,则插入时跳过

javascript - 向数组中的某些字符串值添加前缀 "#"

java - 如何在不执行操作的情况下从 struts.xml 本身返回 HTML 页面?

c - fork() 的意外行为

c - Emacs 心理治疗师 : Where can I find the code?

javascript - 将 PHP 数组传递给 JavaScript 对象数组

java - 静态方法总是加载到内存中吗?

java - JTextField 在静态时在某些页面上消失,而在其他页面上出现

c - llvmgen.c 中的 xmos 内部编译器错误?

c - 内存中的程序及其内存映射