Why do we use _ in variable names?

前端 未结 11 1889
一生所求
一生所求 2020-12-25 11:26

I have seen variables like _ image and was wondering what _ meant?

11条回答
  •  太阳男子
    2020-12-25 11:55

    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.

提交回复
热议问题