C++ Primer 4/e 有这样一个概念:‘Initialization is an important concept in C++ and one to which we will return throughout this book.
Initialized variables are those that are given a value when they are defined. Uninitialized variables are not given an initial value:
int val1 = 0; // initialized int val2; // uninitialized
It is almost always right to give a variable an initial value, but we are not required to do so. When we are certain that the first use of a variable gives it a new value, then there is no need to invent an initial value. For example, our first nontrivial program on page 6 defined uninitialized variables into which we immediately read values.
When we define a variable, we should give it an initial value unless we are certain that the initial value will be overwritten before the variable is used for any other purpose. If we cannot guarantee that the variable will be reset before being read, we should initialize it.’
而中文版的说明如下:‘初始化(initialization) 在C++ 中是个重要概念,本书将一再提及。
已初始化变数是“定义时便获得初值”的变数,未初始化变数则没有获得初值:
int val1 = 0; //已初始化
int val2; //未初始化
“给变数一个初值”几乎永远是正确的行为,但并不是非那么做不可。如果我们很肯定第一次使用某变数时会给它一个值,那么就没有必要为他设想一个初值。例如我们在“p.6”第一个“有所事事”的程式中定义了未初始化变数,随后立刻把值读入。
定义变数时应该给予初值,除非我们确定这个初值在该变数第一次被使用前会被覆盖掉(overwritten)。如果我们无法保证为某变数读取数值之前该变数会被重新设值(reset),就应该将初始化。’
这个观念真的让我很受用,不论是在C 或在其他的语言,纵使是在PHP上也很好用。