dollar sign in variable name?

Valmond picture Valmond · Oct 28, 2011 · Viewed 14.7k times · Source

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?

Answer

James Kanze picture James Kanze · Oct 28, 2011

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 '_'.