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

การประกาศและเริ่มต้นค่าตัวแปรที่ถูกต้องและผิดใน C (Legal vs Illegal)


การประกาศตัวแปร (Declaration)

datatype var1, var2, ...;
  • Local: ในบล็อก (ใช้ได้แค่ในบล็อก)
  • Global: นอกฟังก์ชัน (ใช้ได้ทั่วโปรแกรม)

การเริ่มต้นค่า (Initialization)

datatype var = value;

ตัวอย่าง Legal (ถูกต้อง)

  • char a = 65; - ค่าคงที่ (constant)
  • double x = 30 * PI; - constant expression
  • double arr[] = {1, PI/2, PI, 2*PI/2}; - array init ด้วยค่าคงที่

ตัวอย่าง Illegal (ผิด)

  • static int p = 20, q = p * p; - static ต้อง init ด้วย constant เท่านั้น (p ไม่ใช่ constant)

โปรแกรมทดสอบ Legal

#include <stdio.h>
int main() {
    int a = 10, b = 20;
    printf("%d ", a < b);   // 1
    printf("%d ", a <= b);  // 1
    printf("%d ", a > b);   // 0
    printf("%d ", a >= b);  // 0
    printf("%d ", a == b);  // 0
    printf("%d ", a != b);  // 1
    return 0;
}

ผลลัพธ์

1 1 0 0 0 1

โปรแกรมทดสอบ Illegal

#include <stdio.h>
int main() {
    static int p = 20, q = p * p;  // Error!
    printf("%d %d", p, q);
    return 0;
}

ผลลัพธ์

error: initializer element is not constant
static int p=20, q=p*p;