I stumbled on some C++ code like this:

int $T$S;

First I thought that it was some sort of PHP code or something wrongly pasted in there but it compiles and runs nicely (on MSVC 2008).

What kind of characters are valid for variables in C++ and are there any other weird characters you can use?


Solution 1:

The only legal characters according to the standard are alphanumerics and the underscore. The standard does require that just about anything Unicode considers alphabetic is acceptable (but only as single code-point characters). In practice, implementations offer extensions (i.e. some do accept a $) and restrictions (most don't accept all of the required Unicode characters). If you want your code to be portable, restrict symbols to the 26 unaccented letters, upper or lower case, the ten digits, and the '_'.

Solution 2:

It's an extension of some compilers and not in the C standard

MSVC:

Microsoft Specific

Only the first 2048 characters of Microsoft C++ identifiers are significant. Names for user-defined types are "decorated" by the compiler to preserve type information. The resultant name, including the type information, cannot be longer than 2048 characters. (See Decorated Names for more information.) Factors that can influence the length of a decorated identifier are:

  • Whether the identifier denotes an object of user-defined type or a type derived from a user-defined type.
  • Whether the identifier denotes a function or a type derived from a function.
  • The number of arguments to a function.

The dollar sign is also a valid identifier in Visual C++.

// dollar_sign_identifier.cpp
struct $Y1$ {
    void $Test$() {}
};

int main() {
    $Y1$ $x$;
    $x$.$Test$();
}

https://web.archive.org/web/20100216114436/http://msdn.microsoft.com/en-us/library/565w213d.aspx

Newest version: https://docs.microsoft.com/en-us/cpp/cpp/identifiers-cpp?redirectedfrom=MSDN&view=vs-2019

GCC:

6.42 Dollar Signs in Identifier Names

In GNU C, you may normally use dollar signs in identifier names. This is because many traditional C implementations allow such identifiers. However, dollar signs in identifiers are not supported on a few target machines, typically because the target assembler does not allow them.

http://gcc.gnu.org/onlinedocs/gcc/Dollar-Signs.html#Dollar-Signs

Solution 3:

In my knowledge only letters (capital and small), numbers (0 to 9) and _ are valid for variable names according to standard (note: the variable name should not start with a number though).

All other characters should be compiler extensions.