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

标签 c++ c scope initialization declaration

如果我使用 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/

相关文章:

php - 在所有 Yii View 中都有一个可用的变量

ruby - 在 Ruby 中继承类级实例变量?

c++ - Cmake 中的资源文件夹

c - 在带有文件描述符的 execl 中使用 grep

c++ - 如何将公共(public)接口(interface)的子集暴露给类

c - C 中结构的逻辑运算符

c - 随机数生成器

对象内部的 Javascript/jQuery 事件处理程序范围使用关键字 this

c++ - 分配给 *this 用于构造函数委托(delegate)

c++ - std::function 是如何实现的?