c - 为什么在循环外部和内部声明具有相同名称的变量不会产生错误?

标签 c loops for-loop scope

{  
    int i;  
    for(i=0;i<5;i++)  
    {  
        int i=10;  
        printf("%d",i);  
    }  
}  

我有两个问题

  1. 为什么i没有重新声明错误?
  2. 为什么输出是 10 5 次而不是 10 1 次?

最佳答案

这一切都与标识符的范围有关。标识符只是 C 中赋予实体(对象、函数、typedef 名称等)的名称,根据 C11 6.2.1/1:

The same identifier can denote different entities at different points in the program.

实体的范围在该部分的 /2 中描述:

For each different entity that an identifier designates, the identifier is visible (i.e., can be used) only within a region of program text called its scope.

并且 /4 涵盖您的具体情况:

If an identifier designates two different entities in the same name space, the scopes might overlap. If so, the scope of one entity (the inner scope) will end strictly before the scope of the other entity (the outer scope).

换句话说,类似于:

{
    int i = 42;
    printf ("%d ", i);
    {
        int i = 17;
        printf ("%d ", i);
    }
    printf ("%d\n", i);
}

完全有效,并且将打印 42 17 42。这是因为内部 block 内的标识符 i 位于其自己的范围内,该范围以第一个右大括号结束。

在您的特定情况下,您可以将其视为:

{
    int i;              \
    for(i=0;i<5;i++)     > outer i scope
    {                   /
        int i=10;       \
        printf("%d",i);  > inner i scope
    }                   /
}

内部int i=10有效地在for循环体的持续时间内隐藏外部i。这就是为什么它打印大量 10 而不是 0..4

内部i的作用域在for循环体的右大括号处结束,因此,当for的继续条件满足时检查循环后,它再次看到外部的i。这就是为什么它循环五次而不是一次。

关于c - 为什么在循环外部和内部声明具有相同名称的变量不会产生错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30208481/

相关文章:

c - strcat 溢出?

c - 如何在 C# 中为 DLL 导入指定正确的编码(marshal)处理

Javascript:检查数字数组中缺少的数字数量,以使数组连续

c - 在c中打印满足一定条件的直角三角形

c - 在 libwget 中启用 cookie 会导致段错误

c - putc() 写入错误数据

c - 为什么要打印? (C语言)

javascript - 对将函数应用于所有 li 项目感到困惑

mongodb - 如何迭代 mongodb 文档中的对象?

mysql - 如何在 for 循环和 insert 语句中使用粘贴函数和引号