为什么C中的未初始化的变量仍然产生输出 [英] Why an uninitialized variable in C still produces output

查看:161
本文介绍了为什么C中的未初始化的变量仍然产生输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出为什么即使局部变量i是从来没有在这个C程序intialized,许多系统会打印出 0 1 2 3 4 5 6 7 8 9 有人能解释一下这是为什么?任何帮助AP preciated!

 无效美孚(){
   INT I;
   的printf(%d个,我++);
}
诠释主(){
    诠释J;
    为(J = 1; J< = 10; J ++)富();
}


解决方案

的行为是不确定的。这些统计数字是不相关的。这可能是因为布局和堆栈初始化的,但也可能是任何其他原因,以及

例如,假设:


  1. 有没有检查,如果变量初始化。

  2. 这是一个简单堆栈机。

  3. 堆栈初始化为0。

  4. 变量 I 被分配在栈上,而不是作为一个寄存器。

  5. 当一个函数被调用时,它不会初始化堆栈。

在这种情况下 I 将指向堆栈上的每个时间同一地点,将开始为0,堆栈上的同一位置将由一个每次递增

I'm trying to figure out why even though the local variable i is never intialized in this C program, many systems will print out 0 1 2 3 4 5 6 7 8 9 Can someone explain why this is? Any help is appreciated!

void foo() {
   int i;
   printf("%d ", i++);
}
int main() {
    int j;
    for (j = 1; j <= 10; j++) foo();
}

解决方案

The behavior is undefined. The statistics are irrelevant. It might be because of the layout and the initialization of the stack, but it might be for any other reason as well.

For example, assuming:

  1. There is no check if variables are initialized or not.
  2. This is a simple stack machine.
  3. The stack is initialized to 0.
  4. The variable i is allocated on the stack and not as a register.
  5. When a function is called, it does not initialize the stack.

In such case i will refer to the same place on the stack each time, will start as 0 and the same place on the stack will be incremented each time by one.

这篇关于为什么C中的未初始化的变量仍然产生输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆