Is there any reason to use the 'auto' keyword in C++03?

后端 未结 10 1769
[愿得一人]
[愿得一人] 2020-11-28 02:27

Note this question was originally posted in 2009, before C++11 was ratified and before the meaning of the auto keyword was drast

10条回答
  •  我在风中等你
    2020-11-28 03:10

    auto is a storage class specifier, static, register and extern too. You can only use one of these four in a declaration.

    Local variables (without static) have automatic storage duration, which means they live from the start of their definition until the end of their block. Putting auto in front of them is redundant since that is the default anyway.

    I don't know of any reason to use it in C++. In old C versions that have the implicit int rule, you could use it to declare a variable, like in:

    int main(void) { auto i = 1; }
    

    To make it valid syntax or disambiguate from an assignment expression in case i is in scope. But this doesn't work in C++ anyway (you have to specify a type). Funny enough, the C++ Standard writes:

    An object declared without a storage-class-specifier at block scope or declared as a function parameter has automatic storage duration by default. [Note: hence, the auto specifier is almost always redundant and not often used; one use of auto is to distinguish a declaration-statement from an expression-statement (6.8) explicitly. — end note]

    which refers to the following scenario, which could be either a cast of a to int or the declaration of a variable a of type int having redundant parentheses around a. It is always taken to be a declaration, so auto wouldn't add anything useful here, but would for the human, instead. But then again, the human would be better off removing the redundant parentheses around a, I would say:

    int(a);
    

    With the new meaning of auto arriving with C++0x, I would discourage using it with C++03's meaning in code.

提交回复
热议问题