C 编程中的变量作用域 [英] Variable Scope in C programming

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

问题描述

在c中,当这个代码块运行时,它输出10 10 10 10 10.我认为循环应该在第一次执行后退出,因为我变成了11,但它没有发生.为什么会这样?

In c, when this block of code is run,it outputs 10 10 10 10 10. I think the loop should exit after 1st execution as i becomes 11 but it is not happening. Why it is so?

#include<stdio.h>
int main()
{
  int i; 
  for(i=0;i<5;i++)
  {
     int i=10;  
     printf("%d\t",i);
     i++;
  }
  return;
}

但是当程序如下编写时,输出类似于我的想法(即 10 ).上面的代码和下面显示的代码之间的确切区别是什么?C 如何处理这些变量?如果有人对此进行解释,我会很高兴.

But when program is written as below the output is similar to what i am thinking(i.e.10 ).What is the exact difference between above code and the code shown below? How C is handling these variable? I would be glad if anyone explain about this.

#include<stdio.h>
int main()
{
  int i; 
  for(i=0;i<5;i++)
  {
     i=10;  
     printf("%d\t",i);
     i++;
  }
  return;
}

推荐答案

在您的第一个程序中,for 循环使用了 for<之外声明的 i/code> 来控制循环.printf 使用 for 循环内声明的 i 来打印值,并且这个 i 具有块作用域.

In your first program, for loop is using the i declared outside the for to control the loop. The printf uses the i declared inside the for loop to print the value and this i has block scope.

for loopi 的新声明暂时隐藏了旧声明.现在i 的值为10.在 for 循环块的末尾,新的 i 对程序不可见,变量恢复了它的旧含义,这次 i 存储根据循环迭代的值(1234).

The new declaration of i in the for loop temporarily hides the old declaration. Now the value of i is 10. At the end of the for loop block the new i is not visible to the program and the variable regains its old meaning and this time i stores the value as per the iteration of loop (either 1, 2, 3 or 4).

这篇关于C 编程中的变量作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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