为什么我得到 C 程序的垃圾值?
Why am I getting garbage value for the C program?
为什么用GCC/Clang编译下面的C代码会得到垃圾值?
请注意,如果我只是在内部范围内打印 x 的值,我会得到预期的结果。
#include<stdio.h>
int main()
{
int x = 5;
{
int x = x;
printf("%d", x);
}
return 0;
}
声明 int x = 5;
超出了第二个块的范围。这意味着下面这段代码中的变量x
{
int x = x;
printf("%d", x);
}
不同于外部变量x
,在main中声明。因此,当您尝试在赋值中访问它的值时,它会给出一个垃圾值,因为它之前在此范围内不存在,因此 它没有被初始化.
在此声明中
int x = x;
标识符 x
的声明点在声明符的完整定义之后 x
在赋值符号 =
之前已经可见并且隐藏变量在外部块作用域中声明了相同的名称..
并且您将未初始化的 x
分配给自身。结果它有一个不确定的值。
你可以这样想象
int x;
x = x;
C++ 标准中存在完全相同的示例(3.3.2 声明点)
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 ]
在C标准中有写(6.2.1标识符的范围)
7 Structure, union, and enumeration tags have scope that begins just
after the appearance of the tag in a type specifier that declares the
tag. Each enumeration constant has scope that begins just after the
appearance of its defining enumerator in an enumerator list. Any
other identifier has scope that begins just after the completion of
its declarator.
注意枚举数的定义。枚举器的规则不同。
这个程序是合式的,枚举器 x
将由在外部作用域中声明的变量 x
初始化(而枚举器 y
将由前面的变量初始化枚举数 x
).
#include <iostream>
int main()
{
const int x = 10;
{
enum E { x = x + 1, y = x };
std::cout << "E::x = " << x << ", E::y = " << y << std::endl;
}
std::cout << "x = " << x << std::endl;
}
程序输出为
E::x = 11, E::y = 11
x = 10
为什么用GCC/Clang编译下面的C代码会得到垃圾值? 请注意,如果我只是在内部范围内打印 x 的值,我会得到预期的结果。
#include<stdio.h>
int main()
{
int x = 5;
{
int x = x;
printf("%d", x);
}
return 0;
}
声明 int x = 5;
超出了第二个块的范围。这意味着下面这段代码中的变量x
{
int x = x;
printf("%d", x);
}
不同于外部变量x
,在main中声明。因此,当您尝试在赋值中访问它的值时,它会给出一个垃圾值,因为它之前在此范围内不存在,因此 它没有被初始化.
在此声明中
int x = x;
标识符 x
的声明点在声明符的完整定义之后 x
在赋值符号 =
之前已经可见并且隐藏变量在外部块作用域中声明了相同的名称..
并且您将未初始化的 x
分配给自身。结果它有一个不确定的值。
你可以这样想象
int x;
x = x;
C++ 标准中存在完全相同的示例(3.3.2 声明点)
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 ]
在C标准中有写(6.2.1标识符的范围)
7 Structure, union, and enumeration tags have scope that begins just after the appearance of the tag in a type specifier that declares the tag. Each enumeration constant has scope that begins just after the appearance of its defining enumerator in an enumerator list. Any other identifier has scope that begins just after the completion of its declarator.
注意枚举数的定义。枚举器的规则不同。
这个程序是合式的,枚举器 x
将由在外部作用域中声明的变量 x
初始化(而枚举器 y
将由前面的变量初始化枚举数 x
).
#include <iostream>
int main()
{
const int x = 10;
{
enum E { x = x + 1, y = x };
std::cout << "E::x = " << x << ", E::y = " << y << std::endl;
}
std::cout << "x = " << x << std::endl;
}
程序输出为
E::x = 11, E::y = 11
x = 10