คำอธิบาย
ค่าคงที่ (Constant) หรือ Literals คือค่าที่เมื่อถูกกำหนดแล้ว จะไม่เปลี่ยนแปลงระหว่างการรันโปรแกรม ใช้คำสำคัญ const ในการประกาศ
รูปแบบการประกาศ (Syntax)
const type VariableName; // หรือ const type *VariableName;
ประเภทของค่าคงที่
- Integer constants - จำนวนเต็ม เช่น 1, 0, 34, 4567
- Floating-point constants - จำนวนทศนิยม เช่น 0.0, 156.89, 23.456
- Octal & Hexadecimal constants - ฐานแปดและฐานสิบหก เช่น 0x2a, 0xaa (Hex), 033, 024 (Octal)
- Character constants - ตัวอักษรเดี่ยว เช่น 'a', 'B', 'x'
- String constants - สตริง เช่น "TutorialsPoint"
ตัวอย่างที่ 1: ใช้ค่าคงที่คำนวณค่า
#include <stdio.h>
int main() {
const int number = 45;
int value, data;
printf("enter the data: ");
scanf("%d", &data);
value = number * data;
printf("The value is: %d", value);
return 0;
}
ผลลัพธ์: enter the data: 20 → The value is: 900
ตัวอย่างที่ 2: พยายามเปลี่ยนค่าคงที่ (Error)
#include <stdio.h>
int main() {
const int number = 45;
int data;
printf("enter the data: ");
scanf("%d", &data);
number = number * data; // Error: assignment of read-only variable
printf("The value of number is: %d", number);
return 0;
}
ผลลัพธ์: Error - ไม่สามารถเปลี่ยนค่าตัวแปรที่ประกาศ const ได้