1. 程式人生 > >【C++】C++中變量的聲明與定義的區別

【C++】C++中變量的聲明與定義的區別

分配 int -o sign 變量 range price ios urn

聲明(declaration):意味著告訴編譯器關於變量名稱、變量類型、變量大小、函數名稱、結構名稱、大小等等信息,並且在聲明階段不會給變量分配任何的內存。

定義(definition):定義就是在變量聲明後,給它分配上內存。可以看成“定義 = 聲明 + 內存分配”。

例如:

#include <iostream>
using namespace std;
int addtion(int a,int b);//聲明
struct product{unsigned int weight;double price;};//聲明

int main(){
cout 
<< "addtion is " << addtion(6,8) << endl; product apple,orange;//定義 return 0; } //定義 int addtion(int a,int b){ return a+b; }

上面的案例中,

int addtion(int a,int b);
struct product{unsigned int weight;double price;};

上面是聲明,它們只是告訴編譯器有這個東西,並不會分配內存。

product apple,orange;
int addtion(int
a,int b){return a+b;}

上面是定義,給他們會被分配內存。

聲明和定義還有一種常見的,就是extern修飾的變量。當使用extern關鍵字修飾變量(未初始化),表示變量聲明。當在另一個文件中,為extern關鍵字修飾的變量賦值時,表示變量定義。
例如:
header.h

#ifndef HEADER_H
#define HEADER_H
// any source file that includes this will be able to use "global_x"
int global_x = 20;

#endif

file.h

#include <iostream>
#include 
"header.h" extern int global_x; int main(){ std::cout << "global_x = " << global_x << std::endl; return 0; }

然後用 g++ file.h -o file 編譯後
再用./file運行
結果如下:

global_x = 20;

【C++】C++中變量的聲明與定義的區別