c中的变量隐藏和 "优先权"[重复]

问题描述 投票:2回答:1

下面的程序。

#include <stdio.h>
int main()
{
    char i='u';
    for (int i=0;i<=3;i++)
    {
        printf("%d\n",i);
    }
    return 0;
}

在新的行中打印0,1,2,3, 因为字符变量... i 在for循环外声明的是 "隐藏"。但是,下面的程序。

#include <stdio.h>
int main()
{
    char i='u';
    for (int i=0;i<=3;i++)
    {
        int i=8;
        printf("%d\n",i);
    }
    return 0;
}

在新的行上打印8个 "4",就像变量一样。i 初始化为8,具有 更优先 比变数 i (计数器)从0到3 。

i 中的初始化和 i 顺带 同属一个区块但其中一个似乎比另一个更优先。这种优先权是否真的存在,如果存在,是否有明确的优先顺序?

c variables scope
1个回答
1
投票

你所说的 "优先级 "其实是指的是 范围.

每个变量和函数都有一个包围的作用域,在这个作用域中,变量的名称是有效的,并且它有特定的寿命。 如果一个作用域中的变量与上一个作用域中的变量名称相同,那么外层作用域中的变量被遮挡,只有最内层作用域中的变量可见。

在一个变量在初始化部分声明的情况下,一个 for 循环中,这些变量的作用域在其他部分的 for 以及循环体。 如果循环体是一个复合语句,则以 另一个 作用域,而在这里声明的变量将在更高的作用域掩盖同名变量。

所以在你的第二个程序中,你有三个变量,分别命名为 i:

  • 第一部分的范围 i 是主体的 main 功能。
  • 第二项的范围是: ifor 声明的范围。
  • 第三条的范围 i 是主体的 for 语句。

0
投票

这种优先权是由 范围界定规则:

任何其他标识符的作用域都是在其声明符结束后、初始化器(如果有的话)之前开始。

int x = 2; // scope of the first 'x' begins
{
    int x[x]; // scope of the newly declared x begins after the declarator (x[x]).
              // Within the declarator, the outer 'x' is still in scope.
              // This declares a VLA array of 2 int.
}
unsigned char x = 32; // scope of the outer 'x' begins
{
    unsigned char x = x;
            // scope of the inner 'x' begins before the initializer (= x)
            // this does not initialize the inner 'x' with the value 32, 
            // this initializes the inner 'x' with its own, indeterminate, value
}
 unsigned long factorial(unsigned long n)
// declarator ends, 'factorial' is in scope from this point
{
   return n<2 ? 1 : n*factorial(n-1); // recursive call
}
© www.soinside.com 2019 - 2024. All rights reserved.