c - 申报区别及范围?

标签 c

有问题Declaration difference?有人问

int i;

for (i=0; i<100; i++) {
    //some loop....
}

和:

for (int i=0; i<100; i++) {
    //some loop....
}

答案很明确;第二个是 C99,i 的范围仅限于循环。我没有 C99,所以我无法测试,因此将其作为一个问题提出:在以下情况下的解决方案是什么:

int i = 32;

for (int i=i; i<100; i++) {
    // some loop
}

"new"i 会被“旧”i 初始化吗?或者旧的 i 是否已经不可访问,因为新的 i 已经声明?

最佳答案

在这个for循环语句中

int i = 32;

for (int i = i; i < 100; i++) {
    // some loop
}

在 for 语句中声明的变量 i 具有不确定的值。问题在于,一旦定义了声明符(在本例中,它由标识符 i 组成),它就会在给定范围内隐藏具有相同名称的实体。所以在这个声明中

int i = i;

变量 i 在 = 的右侧引用它自己。

另一个类似的例子。假设您有一个 typedef。

typedef int Int;

你可以在它的定义之后写

Int Int;

在这种情况下,Int 类型对象的名称 Int 隐藏了 typedef 定义,您可能还没有写

Int Another_Int;

因为编译器会报错。

根据C标准(6.2.1标识符的范围)

4 ...If the declarator or type specifier that declares the identifier appears inside a block or within the list of parameter declarations in a function definition, the identifier has block scope, which terminates at the end of the associated block.

C++标准中写的比较清楚(3.3.2 Point of declaration)

1 The point of declaration for a name is immediately after its complete declarator (Clause 8) and before its initializer (if any), except as noted below. [ Example:

int x = 12;
{ int x = x; }

Here the second x is initialized with its own (indeterminate) value. —end example ]

在此代码段中考虑到这一点

int i = 10;

{
    int i[i];
}

在复合语句中声明了数组 int i[10]; 是外部变量 i 用作数组大小,因为内部变量 i 只有在其声明符完成时才会被声明。

关于c - 申报区别及范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31514360/

相关文章:

c - 通过带有类型通知的宏重载 C 中的运算符

c - 如何使用引用运算符在 C 中获取指向字符串的指针?

c - 使用堆溢出写入任意数据

c - 返回除数之和的函数,不带余数,C

C 计数器数组

c - 在c中实现http授权头

c - 从随机维度数组中查找值的索引

c - 将内存重新分配到空引用

c - 在 C 中将 char 数组转换为 ULL 时不匹配,反之亦然

c - C 中的 execvp 无限循环