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

Constant Type Qualifier (const) ในภาษา C

Type qualifiers เพิ่มคุณสมบัติพิเศษให้ datatype: const, volatile, restrict

Const - ค่าคงที่

3 ประเภทค่าคงที่

  1. Literal constants - ค่าตัวเลข/ตัวอักษรโดยตรง: a = b + 7 (7 คือ literal)
  2. Defined constants - #define: #define PI 3.1415
  3. Memory constants - ใช้ const qualifier: const float pi = 3.1415;

Syntax

const type identifier = value;

โปรแกรมตัวอย่าง

#include <stdio.h>
#define PI 3.1415
main() {
    const float cpi = 3.14;
    printf("literal constant = %f\n", 3.14);
    printf("defined constant = %f\n", PI);
    printf("memory constant = %f\n", cpi);
}

ผลลัพธ์

literal constant = 3.140000
defined constant = 3.141500
memory constant = 3.140000