Why do we use _ in variable names?

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

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

相关标签:
11条回答
  • 2020-12-25 11:52

    The underscore in variable names is completely optional. Many programmers use it to differentiate private variables - so instance variables will typically have an underscore prepended to the name. This prevents confusion with local variables.

    0 讨论(0)
  • 2020-12-25 11:53

    Basically it is telling that the developer should provide the definition . In short it defines it does not have any definition .

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-25 11:57

    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_ (since filter 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.

    0 讨论(0)
  • 2020-12-25 11:58

    To avoid reserved keywords, or in reserved keywords, making them more easily avoided. A single underscore is discouraged and reserved in JavaSE9.

    0 讨论(0)
  • 2020-12-25 12:02

    _ usually means something private or internal. In C++ standard libraries all implementation specific variables must start with _.

    0 讨论(0)
提交回复
热议问题