Search code examples
c++cvariablesidentifier

Is `char _3 = 'c'` valid in C and C++?


Considering, i have declared variable name as a numeric with underscore.

#include <stdio.h>

int main()
{
   char _3 = 'c';
   printf("%c\n",_3);
}

I wonder, It's working fine in C and C++. So,is it valid?


Solution

  • All variable names must begin with a letter of the alphabet or an underscore. So yes, it is valid, except if you place it on file scope. (Be careful with double underscore though, it is reserved for the compiler internal use)

    Yet, I wouldn't recommend having variables with names like that, since it may be confusing for the reader.

    From the C++ 2003 standard:

    17.4.3.1.2 Global names [lib.global.names]

    Certain sets of names and function signatures are always reserved to the implementation:

    • Each name that contains a double underscore (_ _) or begins with an underscore followed by an uppercase letter (2.11) is reserved to the implementation for any use.
    • Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace.165

    165) Such names are also reserved in namespace ::std (17.4.3.1).