Why is it bad to start a variable name with a dollar sign in C++/Java and similar such as in PHP?
Edit: Are there any risks?
Why is it bad to start a variable name with a dollar sign in C++/Java and similar such as in PHP?
Edit: Are there any risks?
For java from this post
I don't think there are any risks/side effects; it's just discouraged.
In Java $ is used in inner class names, and probably some "synthetic" method names as well. Basically any code that the compiler has to generate to handle inner classes will have a $ in it. Using the $ would, at the very least be confusing because of that. You should, generally speaking, never need to see a $ in a variables/method/class name in Java.
In Java, using
$
in variables is legal but definitely a bad idea.If you do this, there is a risk that you will accidentally use a name that collides with a name that is used by the compiler itself, or by some code generator. The result will be unexpected compile or runtime failures that could be particularly difficult to diagnose ...
There's also a potential risk that your (mis-)use of
$
will cause problems in future versions of Java. The Java compiler / runtime's use of$
may change in a future, causing your abusive code to fail.Just don't do it. Or at least, don't do it unless you are writing a generator ... and you know what you are getting yourself into.
Because the JLS 8 3.8 says so:
And you can really generate code that fails to compile, e.g. on Oracle JDK 1.8.0_45:
The problem is that
javac
generates a field$assertionsDisabled
to implementassert
, which conflicts with our field.See also: https://stackoverflow.com/a/29439538/895245
In C++, it's non-portable. The only characters the standard says (section
[lex.name]
) must be acceptable to begin an identifier are uppercase and lowercase letters and underscore.The main reasons I can think of are here. In Java, the inner class names are created with $ sign. Also, the $ sign is used for env variables in most of the Oses, so it would be confusing and may intervene the system defined variables.