Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

ประเภทของค่าคงที่ (Constants) ในภาษา C


Constant (ค่าคงที่) = ค่าที่ไม่เปลี่ยนแปลงระหว่างรันโปรแกรม เรียกอีกอย่างว่า Literals

2 ประเภทหลัก

  • Primary Constants: Integer, Float, Character
  • Secondary Constants: Array, Structure, Pointer, Enum, Union

การประกาศด้วย const

const datatype variable = value;

ตัวอย่าง Primary Constants

#include <stdio.h>
int main() {
    const int height = 20;
    const int base = 40;
    float area = 0.5 * height * base;
    printf("Triangle area: %f\n", area);  // 400.000000
    return 0;
}

ตัวอย่าง Secondary Constants (Pointer)

#include <stdio.h>
int main() {
    int a = 10;
    int *p = &a;
    
    printf("a = %d\n", a);    // 10
    printf("p = %p\n", (void*)p);  // address
    
    *p = 12;  // เปลี่ยนค่าผ่าน pointer
    
    printf("a = %d\n", a);    // 12
    printf("p = %p\n", (void*)p);  // address เดิม
    return 0;
}

ผลลัพธ์

a=10
p=0x7ffee...
a=12
p=0x7ffee... (same address)