local int的值应该打印0但是正在打印1.为什么? [英] The value of local int should be printed 0 but it is being printed 1. Why?

查看:109
本文介绍了local int的值应该打印0但是正在打印1.为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C的新手。我已经读过本地int变量被初始化为0但是在这个程序中b被打印1.

I am new to C. I have read that local int variable are initialized to 0 but in this program b is printed 1.

#include<stdio.h>

int main(){
   int b;
   printf("%d ",b);
   int a[10]={1},i; 
   for(i=0;i<10;i++){
      printf("%d ",a[i]);
   }
   printf("%d",b);
}



有人可以解释一下原因吗?

当我删除数组a []和for循环输出是0.为什么?

提前致谢!



我的尝试:



我在删除数组a []和for循环后尝试打印b,然后b打印0但包含数组a []和for循环打印1.


Can someone please explain me the reason?
Also when I remove the array a[] and for loop the output is 0.Why?
Thanks in advance!

What I have tried:

I have tried to print b after removing array a[] and for loop, then b is printed 0 but including the array a[] and for loop it is printed 1.

推荐答案

不会初始化局部变量,因此它们将包含随机值。在使用之前,应始终初始化任何变量。
Local variables will not be initialised so they will contain random values. You should always initialise any variables before you use them.


int b;



您声明了一个变量,但是为它分配了一个值吗?


You declared a variable but do you assign a value to it?


将您的代码更改为

Change your code to
#include<stdio.h>
int main(){
   int b;
   printf("First");
   printf("%d ",b);
   int a[10]={1},i; 
   for(i=0;i<10;i++){
      printf("%d ",a[i]);
   }
   printf("%d",b);
   printf("Last");
}



所以,你知道你看到你的节目打印的所有内容。



有一个工具可以允许您查看代码正在执行的操作,其名称为调试程序。它也是一个很好的学习工具,因为它向你展示了现实,你可以看到哪种期望与现实相符。

当你不明白你的代码在做什么或为什么它做它做的时候,答案就是答案是调试器

使用调试器查看代码正在执行的操作。只需设置断点并查看代码执行情况,调试器允许您逐行执行第1行并在执行时检查变量。



调试器 - 维基百科,免费的百科全书 [ ^ ]



掌握Visual Studio 2010中的调试 - 初学者指南 [ ^ ]

使用Visual Studio 2010进行基本调试 - YouTube [ ^ ]

调试器在这里向您展示您的代码正在做什么,您的任务是与什么进行比较应该这样做。

调试器中没有魔法,它没有找到错误,它只是帮助你。当代码没有达到预期的效果时,你就会接近一个错误。


So that, you know that you see everything your program printed.

There is a tool that allow you to see what your code is doing, its name is debugger. It is also a great learning tool because it show you reality and you can see which expectation match reality.
When you don't understand what your code is doing or why it does what it does, the answer is debugger.
Use the debugger to see what your code is doing. Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute.

Debugger - Wikipedia, the free encyclopedia[^]

Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
Basic Debugging with Visual Studio 2010 - YouTube[^]
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't find bugs, it just help you to. When the code don't do what is expected, you are close to a bug.


这篇关于local int的值应该打印0但是正在打印1.为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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