c++ - 未初始化变量的后果 : int vs unsigned char

标签 c++ initialization language-lawyer undefined-behavior

我在 cppreference.com 上看到了以下示例

int x;     // OK: the value of x is indeterminate
int y = x; // undefined behavior

这里,int y = x;未定义的行为,因为 x 未初始化。

但是,

unsigned char c;     // OK: the value of c is indeterminate
unsigned char d = c; // OK: the value of d is indeterminate

这里,unsigned char d = c;indeterminate behavior,但unsigned char c;也是一个未初始化的变量。

那么,为什么unsigned char d的值是不确定的?

最佳答案

在线引用,如 cppreference.com在一定程度上都很好。但众所周知,有时错误或误解确实偶尔会漏掉。所以在处理这些奇怪的事情时,去官方的 C++ 标准总是一件好事。

N3936

§8.5 Initializers [dcl.init]

12 [...] When storage for an object with automatic or dynamic storage duration is obtained, the object has an indeterminate value , and if no initialization is performed for the object, that object retains an indeterminate value until that value is replaced (5.17). [...] If an indeterminate value is produced by an evaluation, the behavior is undefined except in the following cases:

  • If an indeterminate value of unsigned narrow character type (3.9.1) is produced by the evaluation of

    • [...]

    • the operand of a cast or conversion to an unsigned narrow character type (4.7, 5.2.3, 5.2.9, 5.4)

    • [...]

    then the result of the operation is an indeterminate value.

  • If an indeterminate value of unsigned narrow character type is produced by the evaluation of the right operand of a simple assignment operator (5.17) whose first operand is an lvalue of unsigned narrow character type, an indeterminate value replaces the value of the object referred to by the left operand

  • If an indeterminate value of unsigned narrow character type is produced by the evaluation of the initialization expression when initializing an object of unsigned narrow character type, that object is initialized to an indeterminate value.

Example:

int f(bool b) {
  unsigned char c;
  unsigned char d = c; // OK, d has an indeterminate value
  int e = d; // undefined behavior
  return b ? d : 0; // undefined behavior if b is true
}

所以(令我惊讶的是)标准支持这一点。

至于为什么,最可能的原因也可以在标准中找到:

§3.9.1 Fundamental types [basic.fundamental]

1 [...] For unsigned narrow character types, all possible bit patterns of the value representation represent numbers. These requirements do not hold for other types


作为旁注,我刚刚意识到这可以被邪恶的面试官使用:

问。您能否以明确定义的行为将对象的有效值更改为未确定的值?如果是,怎么做?

一个。

unsigned char ind;
unsigned char x = 24;
x = ind; // x had a valid value, now x has an indetermined value

关于c++ - 未初始化变量的后果 : int vs unsigned char,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45506400/

相关文章:

c++ - 尝试将字符串文字作为模板参数传递

c++ - 在 Linux 中使用 C++ 为 Windows CE 进行开发

c++ - 为什么不允许仅对一个 ref-qualifier 进行重载?

c++ - 在动态分配的 char 数组中保存文件内容的类

c++ - 使用getline输入二维数组

ruby-on-rails - 难以理解在 Ruby 类的初始化(构造函数)中使用 self 和 @ 之间的区别

c++ - 构造函数初始化错误

c - 我应该如何初始化 pthread 互斥量?

c++ - 无法从派生类型的范围访问另一个实例的 protected 成员

c - 退出函数的 noreturn 属性是否必要?