Home > Backend Development > C++ > Why can't C/C++ variables start with a number?

Why can't C/C++ variables start with a number?

王林
Release: 2023-08-25 14:45:09
forward
1882 people have browsed it

Why cant C/C++ variables start with a number?

In C/C, variable names can contain letters, numbers, and the underscore (_) character. There are some keywords in C/C language, except for them, everything is considered as identifier. Identifiers are the names of variables, constants, functions, etc.

We cannot specify identifiers starting with numbers because the compiler has the following seven stages.

  • Lexical analysis
  • Syntax analysis
  • Semantic analysis
  • Intermediate code generation
  • Code optimization
  • Code generation
  • Symbol table

None of the above support variables starting with a number. This is because the compiler confuses whether it's a number or an identifier until it gets to the alphabet following the number. So the compiler will have to backtrack to an unsupported lexical analysis stage. The compiler should be able to recognize the token as an identifier or literal after looking at the first character.

The following is an example demonstrating C language variable declaration.

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;
}
Copy after login

The above program causes the error "Invalid suffix 's' on integer constant" because the variable starts with 5. If we remove it then the program will work normally.

The sample new program demonstrated is as follows.

Example

Live demonstration

#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;
}
Copy after login

Output

The output of the above program is as follows.

The value of variable _4a : 3
The value of variable b : 12
Copy after login

The above is the detailed content of Why can't C/C++ variables start with a number?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template