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

ทำไม C/C++ variables ไม่เริ่มต้นด้วยตัวเลข


ใน C/C++ variable name สามารถมี alphabets, numbers และ underscore(_) ได้ มี keywords บางตัว นอกจากนั้นถือเป็น identifiers Identifiers คือชื่อ variable, constants, functions ฯลฯ

ไม่สามารถระบุ identifier เริ่มต้นด้วยตัวเลขได้ เพราะมี 7 phases ของ compiler:

  • Lexical Analysis
  • Syntax Analysis
  • Semantic Analysis
  • Intermediate Code Generation
  • Code Optimization
  • Code Generation
  • Symbol Table

ไม่มี phase ใดรองรับ variable เริ่มต้นด้วยตัวเลข เพราะ compiler สับสนว่าเป็น number หรือ identifier จนกว่าจะเจอ alphabet หลังตัวเลข compiler ต้อง backtrack ไป lexical analysis phase ซึ่งไม่รองรับ Compiler ควรระบุ token เป็น identifier หรือ literal ได้จาก first character

ตัวอย่าง variable declarations ใน C:

ตัวอย่าง

#include <stdio.h> int main() {    int 5s = 8;    int _4a = 3;    int b = 12;    printf("The value of variable 5s : %d", 5s);    printf("The value of variable _4a : %d", _4a);    printf("\nThe value of variable b : %d", b);    return 0; }

โปรแกรมข้างต้น error “invalid suffix "s" on integer constant” เพราะ variable เริ่มด้วย 5 ถ้าลบออก โปรแกรมจะทำงานถูกต้อง

ตัวอย่าง

#include <stdio.h> int main() {    int _4a = 3;    int b = 12;    printf("The value of variable _4a : %d", _4a);    printf("\nThe value of variable b : %d", b);    return 0; }

ผลลัพธ์

The output of the above program is as follows.

The value of variable _4a : 3 The value of variable b : 12