1. 程式人生 > >【C++】C++中變數的宣告與定義的區別

【C++】C++中變數的宣告與定義的區別

宣告(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;