Why C/C++ variables doesn’t start with numbers

CC++Server Side Programming

In C/C++, a variable name can have alphabets, numbers and underscore( _ ) character. There are some keywords in C/C++ language, apart from them everything is treated as identifier. Identifiers are the name of variable, constants, functions etc.

We can not specify the identifier which starts with a number because there are seven phases of compiler as follows.

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

None of above supports that a variable starts with a number. This is because the compiler gets confused if is a number or identifier until it reaches an alphabet after the numbers. So the compiler will have to backtrack to the lexical analysis phase which is not supported. The compiler should be able to identify a token as an identifier or a literal after looking at the first character.

The following is an example to that demonstrates variable declarations in C.

Example

#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;
}

The above program leads to an error “invalid suffix "s" on integer constant” because a variable starts with 5. If we remove this, then the program will work correctly.

An example that demonstrates the new program is as follows.

Example

 Live Demo

#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;
}

Output

The output of the above program is as follows.

The value of variable _4a : 3
The value of variable b : 12
raja
Published on 21-Nov-2018 17:11:29
Advertisements