Cyb*_*mot 5 c++ double undefined
我想问为什么使用未初始化的变量被认为是非类型安全的?
我正在阅读本网站上的C++书籍指南中的Bjarne Stroustrup的初学者书(Programming Principles and Practice Using C++).
书中有关于类型安全的部分说明:
程序 - 或程序的一部分 - 在仅根据类型规则使用对象时是类型安全的.例如,在初始化之前使用变量不被视为类型安全的.
然后本书提供了以下代码作为示例:
int main() {
double x; // we "forgot" to initialize
// the value of x is undefined
double y = x; // the value of y is undefined
double z = 2.0+x; // the meaning of + and the value of z are undefined
}
Run Code Online (Sandbox Code Playgroud)
我知道未初始化的局部变量将具有不确定的值,并且读取此变量将导致未定义的行为.我不明白的是它是如何与类型安全相关联的.我们仍然知道变量定义中的类型.
为什么上面代码中的注释表明当2.0和x都是double时,+的含义是未定义的,+是为double + double定义的?
未定义的行为意味着输出可能是您所期望的,也可能是某个类型的有效范围之外的不确定值。
未定义行为的一个明显例子是有符号整数溢出:
unsigned int i; // uninitialized
int x = i + 2; // indeterminate value
if (x + 1 > x) {} // undefined behavior due to signed overflow
Run Code Online (Sandbox Code Playgroud)
xint如果i保留最大值 ,则可以具有超出有效范围的值unsigned int。
因此,对于具有不确定值的表达式,不能保证类型安全。