0
点赞
收藏
分享

微信扫一扫

C语言 标识符的作用域

#include <stdio.h> 

int&nbsp;x&nbsp;=&nbsp;20;

void&nbsp;print_x(void){
puts(&quot;------print_x函数调用文件作用域------&quot;);&nbsp;
printf(&quot;x&nbsp;=&nbsp;%d\n&quot;,&nbsp;x);
}

int&nbsp;main(void){
int&nbsp;i;
int&nbsp;x&nbsp;=&nbsp;88;

print_x();

puts(&quot;-------main函数调用块作用域-----------&quot;);&nbsp;
printf(&quot;x&nbsp;=&nbsp;%d\n&quot;,&nbsp;x);


puts(&quot;---for循环体打印for循环体内部块作用域---&quot;);&nbsp;

for&nbsp;(i&nbsp;=&nbsp;0;&nbsp;i&nbsp;&lt;&nbsp;5;&nbsp;i++){
int&nbsp;x&nbsp;=&nbsp;i&nbsp;*&nbsp;100;
printf(&quot;x&nbsp;=&nbsp;%d\n&quot;,&nbsp;x);
}

puts(&quot;---------main函数调用块作用域-----------&quot;);&nbsp;
printf(&quot;x&nbsp;=&nbsp;%d\n&quot;,&nbsp;x);
}

运行结果:
C语言 标识符的作用域_函数体
由于print_x函数内没有定义变量,所以会引入 函数体外定义的变量 x = 20;
当在main函数内部打印x变量时,会在内部寻找是否定义了x 变量 如果有,则会就近原则打印main 内部定义的变量,如果没有 则会打印 main 函数体外面的变量。
for循环会打印循环体中的变量,当for语句的循环结束之后,该变量 x 的名称就会失效。
所以在调用最后一个printf函数时,x值显示的是mian函数内定义 x = 88;

#include <stdio.h> 

int&nbsp;x&nbsp;=&nbsp;20;

int&nbsp;main(void){

puts(&quot;-------调用函数外层的变量-----------&quot;);&nbsp;
printf(&quot;x&nbsp;=&nbsp;%d\n&quot;,&nbsp;x);

int&nbsp;x&nbsp;=&nbsp;88;

puts(&quot;---------调用函数内层的变量------------&quot;);&nbsp;
printf(&quot;x&nbsp;=&nbsp;%d\n&quot;,&nbsp;x);
}

运行结果:
C语言 标识符的作用域_作用域_02

总结:

  1. 如果 两个同名变量分别拥有文件作用域和块作用域,那么只有拥有块作用域的变量是 “可见” 的,而拥有文件作用域的变量会被 “隐藏” 起来。
  2. 当同名变量都被赋予了块作用域的时候,内层的变量是“可见”的,而外层的变量会被 “隐藏” 起来。
  3. 函数会就近原则,先找函数体内是否存在定义的变量,如果没有,则会寻找函数体外层的变量,如果都没有,程序会报错。
  4. 程序是从上往下逐条执行的
    如果在引用变量的下方定义了变量,没有在上方定义变量,则不会调用函数体下方的变量。


举报

相关推荐

0 条评论