天天看點

C++變量與常量

變量

C++變量的聲明的作用就是告訴編譯器在哪裡建立和如何建立變量的存儲。變量的聲明指定一個資料類型和該類型的一或多個變量清單,如:

int i,j,k;
           

變量在聲明時初始化,即用上指派符号和一個常量表達式:

int d = 3,f = 6;
           

在哪裡定義變量

一般來說有三處地方可以聲明變量:

  1. 在函數或一個代碼塊内部(局部變量)
  2. 在函數參數的定義中聲明變量(形式參數)
  3. 在所有函數外部聲明變量(全局變量)

局部變量

#include <iostream>
using namespace std;
int main()
{
	int a,b; // 局部變量
	...
}
           

形式參數

#include <iostream>
using namespace std;
int helloWorld(int day) // 形式參數
{
	...
}
           

全局變量

#include <iostream>
using namespace std;

int x; // 全局變量
int main() 
{
	...
}
           

預設值

static int a; // a的預設值為 NULL,即所有位元組都是0
int b; // b的預設值為未定義
           

常量

  1. #define宏常量:#define 常量名 常量值
  2. const修飾的變量:const 資料類型 常量名 = 常量值

繼續閱讀