นี่คือความแตกต่างระหว่าง enum, const และ #define ในโปรแกรม C หรือ C++ สร้างความสับสนเมื่อต้องตัดสินใจเลือก มาดูว่าทั้งสามคืออะไร
const หรือ static const
const เป็นข้อมูลแบบคงที่ static const คือคงที่แต่ storage specifier เป็น static จะคงอยู่จนโปรแกรมจบ และข้อมูลแบบคงที่ไม่สามารถอัปเดตได้
ตัวอย่าง
#include <iostream>
using namespace std;
main() {
int x;
x = 65700;
cout << "x is (as integer):" << x << endl;
x = (short)65700; // จะถูกปัดหลัง 2 ไบต์
cout << "x is (as short):" << x << endl;
}
ผลลัพธ์
x is (as integer):65700 x is (as short):164