Why do we use _ in variable names?
Some people use it to indicate that they are variables rather than (say) method names. Or to make it obvious that they're instance variables rather than local variables. Sometimes you see extra prefixes, e.g.
private int m_age; // Member (instance) variable
private static int g_maxAge; // Global (static) variable
It's just a convention. I was going to say "there's nothing magic about _" but that's not quite true - in some languages a double underscore is reserved for "special" uses. (The exact usage depends on the language of course.)
EDIT: Example of the double underscore rule as it applies to C#. From the C# 4 spec, section 2.4.2:
Identifiers containing two consecutive underscore characters (U+005F) are reserved for use by the implementation. For example, an implementation might provide extended keywords that begin with two underscores.
It doesn't mean anything. It is rather a common naming convention for private member variables to keep them separated from methods and public properties. For example:
class Foo
{
private int _counter;
public int GetCounter()
{
return _counter;
}
public int SetCounter(int counter)
{
_counter = counter;
}
}
In most languages _
is the only character allowed in variable names besides letters and numbers. Here are some common use cases:
- Separating words:
some_variable
- Private variables start with underscores:
_private
- Adding at the end to distinguish from a built-in name:
filter_
(sincefilter
is a built-in function) - By itself as an unused variable during looping:
[0 for _ in range(n)]
Note that some people really don't like that last use case.