了解For循环在C中 [英] Understanding For loop in C

查看:149
本文介绍了了解For循环在C中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  int j = 20;我有一点困难, 
for(int i = 0,j; i <= j; i ++,j--)
printf(i =%d and j =%d \\\
,i,j)

将输出打印为

  i = 0和j = 2 
i = 1和j = 1



<为什么它不是以 j = 20 开头,而是打印 j = 2 并在 j = 1



但是当我用这个代码的时候

  int j = 20; 
for(int i = 0,j = 20; i <= j; i ++,j--)
printf(i =%d and j =%d \\\
,i,j );

它以

  i = 0 and j = 20 upto ... i = 9 and j = 11 

是否有我缺少的东西?

解决方案

在for构造中声明j会创建一个新的(有作用域的)j,它有一个与outer不同的值。如果你没有初始化它,你就会得到分配后在内存中发生的任何垃圾。

这样的变量被称为自动变量,并被分配到程序的叠加。当你需要一个,分配更多的堆栈空间。当它们超出范围(当函数返回的时候),它们会被弹出来清除。

当需要下一个自动存储时,同样的事情发生,然后你得到堆栈中遗留的任何位模式作为新的变量值。

I am having little difficulty in figuring out following piece of simple for loop code in C.

int j=20;
for(int i=0, j; i<=j ; i++, j--)     
    printf("i = %d and j = %d \n",i,j);                     

Prints output as

i=0 and j=2
i=1 and j=1

Why it does not starts with j=20 and rather prints j=2 and stops after j=1.

But when I use this code

int j=20;
for(int i=0, j=20; i<=j ; i++, j--)     
    printf("i = %d and j = %d \n",i,j);   

It starts properly with

i=0 and j=20 upto ... i=9 and j= 11

Is there something that I am missing ?

解决方案

You are. Declaring j inside of the for construct creates a new (scoped) j, which has a value different from the outer. If you fail to initialize it, you get whatever crap happened to be in memory when allocated.

Variables like this are called "automatic" variables, and are allocated on the program's stack. As you need one, more stack space is allocated. When they go out of scope (really when the function returns), they are cleaned up by popping them all back off.

When the next bit of automatic storage is needed, the same thing happens and you then get whatever bit pattern happened to be left over on the stack as your new variables value.

这篇关于了解For循环在C中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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