I’ve been taught since high school that defining variables like this:
int _a;
or
int __a;
should be consider bad practice because this would eventually puzzle compilers that use variables starting with an underscore to name temporary variables.
As far as I know this is the reason why some people like to move the underscore at the end of the name, like:
int a_;
However, I see a lot of code all around that makes use of underscore-starting variables. And that code builds fairly well with both Visual Studio 2010 and g++ 4.x.
So I wonder: is this a non-issue nowadays? Are modern compilers smarter about naming conventions?
4
You are apparently misunderstanding the reason prefix underscores are bad practice.
To make it short, it is because the C and C++ standard reserve these prefix for implementation details, for example for standard library implementation. (note that _ and __ are not reserved for the same things, see comments)
Even if the names are under scope (namespace, class, etc.), there can be some global names, in particular macros, which use these prefix and might silently break your code if you use them too.
So, basically, most of the time it is safe to use these prefix BUT if you don’t use them you have a 100% guarantee that your naming will never conflict with the implementation names.
Which is why, in doubt, don’t use these prefix.
7
Using two underscores is definitely bad – that is reserved for compiler-specific implementation details. This does not apply to using one underscore.
Some people have a hate on for underscores. Whether you call something m_index
or highest_price
or _a
– they detest it. I worked with someone 25 years ago who told me about a specific IBM printer (a very popular one) that fit more lines on the page by omitting the bottom pixel on every other line. This was fine for memos, or for output of big swathes of numbers and such, but had the effect for code of making half of your underscores invisible. (Yes, really!) People from that generation generally have the irrational underscore hate, either from interaction with that printer or from working with someone who beat into them that underscores are not to be used.
Most people find using mixed case (an option we didn’t have in, say, Fortran) a more readable approach: mIndex
, HighestPrice
, a
stand up pretty well to the earlier underscored examples. I will give you two rules:
- never start anything (function, variable, macro, typedef) with two underscores
- pick a consistent convention ( eg
_limit
for function parameters,m_limit
for member variables, never use underscores, camel case, capitalize every word, Hungarian, something) and stick to it. Don’t bop around sometimes with underscores at the beginning, sometimes the end, sometimes not using them, and five different casing conventions. Be consistent.
The printer in question is long gone. If you like to use one underscore at time, feel free to. But understand, underscore haters still exist.
7