列舉 vs. const vs. #define 在 C/C++ 中


在這裡,我們會看到在 C 或 C++ 程式中列舉、常量和 #define 之間有什麼區別。在需要做出選擇時,這三者可能會帶來困惑。現在讓我們看看這三者是什麼。

const 或 static const

const 是常量型別資料,或者 static const 是常量,但儲存規範符為 static。所以它將保持活動狀態直到程式終止,且常量型別資料無法更新。

示例

#include <iostream>
using namespace std;
main() {
   int x;
   x = 65700;
   cout << "x is (as integer):" << x << endl;
   x = (short)65700; //will be rounded after 2-bytes
   cout << "x is (as short):" << x << endl;
}

輸出

x is (as integer):65700
x is (as short):164

更新於: 30-Jul-2019

516 次瀏覽

開啟您的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.