c 中的变量隐藏和"priority"



以下程序:

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

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

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

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

for初始化中的i和for循环中的i位于同一块中,但其中一个似乎比另一个具有更高的优先级。这样的优先权真的存在吗?如果存在,是否有明确的优先顺序?

您所称的"优先级"实际上被称为scope

每个变量和函数都有一个封闭范围,名称在其中是有效的,并且在其中具有特定的生存期。如果一个作用域中的变量与更高作用域的变量具有相同的名称,则外部作用域上的变量将被屏蔽,并且只有最内部作用域中可见的变量。

for循环的初始化部分中声明的变量的情况下,这些变量的作用域在for的其他部分以及循环体中都可见。如果循环体是一个复合语句,它将启动另一个作用域,并且此处声明的变量将在更高的作用域中屏蔽具有相同名称的变量。

因此,在第二个程序中,有三个名为i:的变量

  • 第一个i的作用域是main函数的主体
  • 第二个i的作用域是for语句
  • 第三个i的作用域是for语句的主体

此类优先级由作用域规则定义:

任何其他标识符的作用域都开始于其声明符的末尾之后和初始值设定项之前(如果有的话(:

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
}

最新更新