- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
有问题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/
我正在编写一些代码,用于将 Silverlight View 绑定(bind)到 MVP 模式中的演示者。在这种特殊情况下,一遍又一遍地执行此操作是一项非常漫长的练习: 型号: public bool
我是一名优秀的程序员,十分优秀!