「Hello World」程式雖然能輸出文字,但真實世界的程式設計遠不止於此。為了撰寫能執行實用任務的程式,我們必須引入變數的概念。
想像一下:我要求你在腦海中記住數字 5,再記住 2。你已在記憶體中儲存了兩個數值。接著我要求你在第一個數值上加 1,你應記住 6(5+1)與 2。最後將兩數相減,得到 4。這個腦海運作過程,與電腦使用兩個變數處理資料的方式如出一轍。用 C++ 表達如下:
a = 5;
b = 2;
a = a + 1;
result = a - b;
雖然這只是簡單的整數運算,但電腦可同時儲存成千上萬個數值並進行複雜運算。我們可將變數定義為:記憶體中用於儲存確定值的一塊區域。
每個變數需要唯一識別子以區別彼此。有效識別子由字母、數字、底線(_)組成,長度無限制(部分編譯器僅識別前 32 字元)。規則如下:
RESULT、result、Result 是三個不同變數asm, auto, bool, break, case, catch, char, class, const, const_cast,
continue, default, delete, do, double, dynamic_cast, else, enum, explicit,
extern, false, float, for, friend, goto, if, inline, int, long, mutable,
namespace, new, operator, private, protected, public, register, reinterpret_cast,
return, short, signed, sizeof, static, static_cast, struct, switch, template,
this, throw, true, try, typedef, typeid, typename, union, unsigned, using,
virtual, void, volatile, wchar_t, while
另需避免使用運算子替代表示法(如 and, or, not 等)作為識別子。
宣告變數時必須指定資料型別,因為不同型別佔用記憶體大小不同。電腦記憶體以位元組為單位組織,1 位元組可儲存單一字元或小整數(0~255)。透過組合多個位元組可表示長整數、浮點數等複雜型別。
| 型別名稱 | 位元組數* | 說明 | 範圍* |
|---|---|---|---|
char | 1 | 字元或 8 位元整數 | 有號:-128~127 無號:0~255 |
short int (short) | 2 | 短整數,16 位元 | 有號:-32,768~32,767 無號:0~65,535 |
long int (long) | 4 | 長整數,32 位元 | 有號:-2,147,483,648~2,147,483,647 無號:0~4,294,967,295 |
int | 4 | 整數 | 同 long |
float | 4 | 單精度浮點數 | 3.4e±38 (7 位有效數字) |
double | 8 | 雙精度浮點數 | 1.7e±308 (15 位有效數字) |
long double | 8 | 長雙精度浮點數 | 1.7e±308 (15 位有效數字) |
bool | 1 | 布林值 | true 或 false |
wchar_t | 2 | 寬字元(國際字元) | 1 個寬字元 |
* 位元組數與範圍可能因系統架構而異,表列為 32 位系統常見值。標準規定:char ≤ short ≤ int ≤ long,浮點數同理遞增。
整數型別(char, short, int, long)可加 signed(可正負)或 unsigned(僅非負)修飾。預設為 signed。例外:char 型別獨立存在,與 signed char、unsigned char 不同。
unsigned short NumberOfSons;
signed int MyAccountBalance; // 等同於 int MyAccountBalance;
語法:型別 識別字;。可一次宣告多個同型別變數,以逗號分隔:
int a;
float mynumber;
int a, b, c; // 等同於分三行宣告
C++ 允許在程式碼任何位置宣告變數(不同於 C 僅能在區塊開頭),但建議遵循傳統習慣集中宣告,利於除錯。
{ })內,僅在該區塊內有效。函式參數亦屬區域變數。extern 關鍵字。區域變數若未初始化,值為未定義。C++ 提供兩種初始化語法:
// C 風格
int a = 0;
// 建構函數風格
int a (0);
兩者在 C++ 中等價。
字串非基本型別,但 std::string 類別提供了極佳的字串操作支援。使用前需包含 <string> 標頭並使用 std 命名空間。
#include
#include
using namespace std;
int main() {
string mystring = "This is a string";
cout << mystring;
return 0;
}
字串支援與基本型別相同的初始化與指派操作:
string s1 = "Hello";
string s2("World");
string s3;
s3 = "New content";