首頁 / CompScience / Programming / Languages / C_and_CPP / Initialized and Uninitialized Variables

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; //未初始化
「給變數一個初值」幾乎永遠是正確的行為,但並不是非那麼做不可。如果我們很肯定第一次使用某變數時會給它一個值,那麼就沒有必要為他設想一個初值。例如我們在「p.6」第一個「有所事事」的程式中定義了未初始化變數,隨後立刻把值讀入。

定義變數時應該給予初值,除非我們確定這個初值在該變數第一次被使用前會被覆蓋掉(overwritten)。如果我們無法保證為某變數讀取數值之前該變數會被重新設值(reset),就應該將初始化。』

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

Print Friendly, PDF & Email
馬上成為工作達人的Fans

About flylinux

發表迴響

你的電子郵件位址並不會被公開。 Required fields are marked *

*

這個網站採用 Akismet 服務減少垃圾留言。進一步瞭解 Akismet 如何處理網站訪客的留言資料

Scroll To Top