Uninitialized Variables Cause Run-Time Problems

C++ Primer 4/e 在变数这里有一个警告:‘

Using an uninitialized object is a common program error, and one that is often difficult to uncover. The compiler is not required to detect a use of an uninitialized variable, although many will warn about at least some uses of uninitialized variables. However, no compiler can detect all uses of uninitialized variables.

Sometimes, we’re lucky and using an uninitialized variable results in an immediate crash at run time. Once we track down the location of the crash, it is usually pretty easy to see that the variable was not properly initialized.

Other times, the program completes but produces erroneous results. Even worse, the results can appear correct when we run our program on one machine but fail on another. Adding code to the program in an unrelated location can cause what we thought was a correct program to suddenly start to produce incorrect results.

The problem is that uninitialized variables actually do have a value. The compiler puts the variable somewhere in memory and treats whatever bit pattern was in that memory as the variable’s initial state. When interpreted as an integral value, any bit pattern is a legitimate valuealthough the value is unlikely to be one that the programmer intended. Because the value is legal, using it is unlikely to lead to a crash. What it is likely to do is lead to incorrect execution and/or incorrect calculation.’

中文版的是这样说:‘使用未初始化物件是个常见的程式错误,也是很难发现的一种错误。编译器并没有要求侦测“未初始化变数的使用”。虽然很多编译器会对某些未初始化变数的使用发出警告,然而没有任何编译器能够侦测出所有未初始化变数的使用。

有时候我们很幸运地在使用一个未初始化变数时立刻于执行期当掉。只要追踪崩溃点,通常很容易就可以发现变数未被适当初始化。

但很多时候程式顺利执行,并产生错误结果。更糟的是在某一台机器上执行产生正确的结果,换到另一台却出错。如果急病乱投医,在不相干位置加入程式码,很可能造成原本正确的程式突然开始产生不正确的结果。

问题在于未初始化变数其实有一个值。编译器首先把变数“放在”记忆体某处,然后把那块记忆体的bit样式(无论它是什么)当作那个变数的初值。任何bit样式(bit pattern)被当作整数来诠释时都是合理的 – 虽然那不是程式员所希望得到的值。因为其值合法,所以使用他不太容易造成程式崩溃。比较可能的是导致不正确的执行和(或)不正确的计算结果。’

写PHP的时候常常会不注意给初值,但也很少很错误,所以就会常忘记,特别是回来写C 或C++就特别容易错误,这是一个很好的警告。