Initialized and Uninitialized Variables

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; //未初始化


這個觀念真的讓我很受用,不論是在C 或在其他的語言,縱使是在PHP上也很好用。