gpt4 book ai didi

c++ - 为什么我得到的 C 程序值是垃圾值?

转载 作者:行者123 更新时间:2023-11-30 20:01:01 25 4
gpt4 key购买 nike

如果我使用 GCC/Clang 编译以下 C 代码,为什么会得到垃圾值?请注意,如果我只是在内部范围中打印 x 的值,我会得到预期的结果。

#include<stdio.h>
int main()
{
int x = 5;
{
int x = x;
printf("%d", x);
}
return 0;
}

最佳答案

在此声明中

int x = x;

标识符x的声明点是在声明符的完整定义之后,即x在赋值符号=之前已经可见> 并隐藏在外部 block 作用域中声明的同名变量..

并且您将未初始化的 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

关于c++ - 为什么我得到的 C 程序值是垃圾值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36304511/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com