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

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

Syntax

Valid identifier naming rules in C ?

// Valid identifier patterns:
[a-zA-Z_][a-zA-Z0-9_]*

// Valid examples:
variable_name, _count, num1, my_var
// Invalid examples:
1variable, 2name, 3_count

Why Variables in C/C++ Can't Start with Numbers?

In C and C++, variable names (also known as identifiers) cannot start with a digit due to how the compiler processes code during compilation.

The Lexical Analysis phase is responsible for reading the source code and breaking it into tokens (like identifiers, keywords, literals, etc.). The compiler needs to distinguish between numeric literals and identifiers immediately upon seeing the first character.

Technical Reasons

We cannot specify an identifier that starts with a number in C/C++ because ?

  • When the lexer encounters a digit, it expects a numeric literal to follow
  • If alphabetic characters appear after digits, the parser gets confused between a number and an identifier
  • This would require backtracking in the lexical analysis phase, which is not supported by most compilers
  • The compiler should be able to identify a token as an identifier or literal after looking at the first character

Example 1: Invalid Variable Names Starting with Numbers

This example demonstrates what happens when we try to create a variable starting with a digit ?

#include <stdio.h>

int main() {
    int 5s = 8;        // Invalid: starts with number
    int _4a = 3;       // Valid: starts with underscore
    int b = 12;        // Valid: starts with letter
    
    printf("This code will not compile due to invalid identifier '5s'\n");
    return 0;
}
Compilation Error:
error: invalid suffix "s" on integer constant

Example 2: Valid Variable Names

This example shows valid identifier naming conventions ?

#include <stdio.h>

int main() {
    int _4a = 3;       // Valid: starts with underscore
    int var2 = 15;     // Valid: starts with letter
    int number_1 = 25; // Valid: starts with letter
    
    printf("The value of variable _4a: %d\n", _4a);
    printf("The value of variable var2: %d\n", var2);
    printf("The value of variable number_1: %d\n", number_1);
    
    return 0;
}
The value of variable _4a: 3
The value of variable var2: 15
The value of variable number_1: 25
Updated on: 2026-03-15T10:03:16+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements