"for"变量的范围在"for"中表示.环形 [英] Scope of variables in "for" loop

查看:86
本文介绍了"for"变量的范围在"for"中表示.环形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我知道的是,块中的多个声明会产生错误消息,并且未初始化的局部变量也会在打印时产生垃圾值.

What I have known so far is, multiple declarations inside a block produce an error message and also uninitialized local variable gives garbage value on printing.

但是碰到C中for循环的示例,这使我对变量范围的概念产生了动摇.

But coming across an example of for loop in C has shaken my concept on the scope of variables.

下面是相同的代码:

#include<stdio.h>

int main()
{
    int i;
    for(int i = 5; i > 0 ; i--){
        int i;
        printf("%d ", i);
    }
}

上面的代码产生输出

0 0 0 0 0

我有两个问题

  1. 一个for循环被视为一个块,那么如何为两个相同变量i的声明分配两个不同的内存?如果将for循环的第一行及其主体视为两个块,那么如何识别不同的块?

  1. A for loop is considered as one block then how two different memories are allocated for two declarations of same variable i? And if the first line of for loop and its body are considered as two blocks, then how to identify different block?

在循环主体中,变量i未初始化,那么如何将值设为0,因为它应该具有垃圾值?

Inside the body of the loop, the variable i is uninitialized, then how is it taking the value as 0, as it should be having garbage value?

请解释一下.

推荐答案

for循环的第一部分中声明的变量的范围是for的所有三个部分以及循环体.在您的情况下,循环的主体是复合语句,您在该块中声明了另一个名为i的变量,因此它屏蔽了在for中声明的i.

The scope of a variable declared in the first part of the for loop is all three parts of the for plus the loop body. In your case the body of the loop is a compound statement, and you declare another variable named i in that block, so it masks the i declared in the for.

因此,在您的代码段中,存在三个相关范围:

So in your piece of code there are three relevant scopes:

  1. main函数的正文
  2. for循环的三个部分.
  3. for循环的主体.
  1. The body of the main function
  2. The three parts of the for loop.
  3. The body of the for loop.

它们中的每一个都是彼此内部"的,因此在这些作用域之一中声明的变量会在较高范围中掩盖同名变量.

And each of them is "internal" to the other, so a variable declared at one of these scopes masks a variable of the same name in a higher scope.

为进一步说明这一点,如果我们按如下方式修改您的代码:

To further illustrate this, if we modify your code as follows:

int main()
{
    int i = 9;
    printf("outer i: %d\n", i);
    for(int i = 5;i>0;printf("middle i:%d\n", i),i--){
        int i = 7;
        printf("inner i: %d\n",i);
    }
    printf("outer i: %d\n", i);
}

输出为:

outer i: 9
inner i: 7
middle i:5
inner i: 7
middle i:4
inner i: 7
middle i:3
inner i: 7
middle i:2
inner i: 7
middle i:1
outer i: 9

关于您的代码为何在循环内打印0的原因,未初始化的变量可能具有任何值,包括0.所以,仅因为它打印0并不意味着它不是垃圾.

As for why your code is printing 0 inside of the loop, an uninitialized variable may have any value, including 0. So just because it's printing 0 doesn't mean it's not garbage.

这篇关于"for"变量的范围在"for"中表示.环形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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