Is _ (single underscore) a valid C++ variable name?

前端 未结 6 1756
挽巷
挽巷 2021-01-07 19:06

With gcc 4.7.2 this compiles just fine for me:

int main()
{
  int _ = 1;
  return 0;
}

Can I expect this to compile in general? I\'ve read

相关标签:
6条回答
  • 2021-01-07 19:49

    Yes, _ is a valid identifier, since it meets the syntax requirements. Basically, an identifier consists of an underscore or letter, followed by zero or more other characters that can be underscores, letters or digits. (As of C++ 2011, identifiers can also contain universal character names and other implementation-defined characters, but that's not relevant to your question.)

    But it's probably not one that you should use in your own code, unless you're very careful.

    As this answer says, quoting the 2003 C++ standard:

    Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace.

    Your _ variable isn't in the global namespace, so you're safe in this case, but it's a good idea to avoid defining any identifiers starting with an underscore.

    Also, I believe GNU gettext (which provides support for localized messages) uses the name _ for its own purposes. (It was arguably a bad idea for GNU gettext do to this, but it was a convenient choice.)

    0 讨论(0)
  • 2021-01-07 19:55

    Yeah it's a valid prefix. Running

    #include <iostream>
    
    using namespace std;
    
    int main()
    {
    char* _ = "Hello World";
    cout << _ << endl; 
    return 0;
    }
    

    prints out "Hello World" as expected. It's not a very helpful varible name but it is valid

    0 讨论(0)
  • 2021-01-07 19:59

    But why having this weird name '_' for a variable? Does it mean you do not want no one access it again or something? Saw code looks like:

    for (auto _ : <range based container>) {
        // some code that does not have '-' at all
    }
    
    0 讨论(0)
  • 2021-01-07 20:01

    According to Stroustrup (3rd edition, section 4.9.3), an identifier consists of a sequence of letters and digits. The first character must be a letter. The underscore character is considered a letter.

    So, yes, it should be portable.

    0 讨论(0)
  • 2021-01-07 20:02

    Yes, from The C++ Programming Language, 4th Edition:

    A name (identifier) consists of a sequence of letters and digits. The first character must be a letter. The underscore character, _, is considered a letter.

    0 讨论(0)
  • 2021-01-07 20:08

    Yes. a single _ will be accepted as variable or any identifier/namespace name! E.g. google mock uses this.

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