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

后端 未结 10 1770
[愿得一人]
[愿得一人] 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:20

    Is there some other meaning to 'auto' other than 'local variable?'

    Not in C++03.

    Anything it does that isn't implicitly done for you wherever you may want to use it?

    Nothing whatsoever, in C++03.

    How does an auto variable behave in program scope? What of a static auto variable in file-scope?

    Keyword not allowed outside of a function/method body.

    Does this keyword have any purpose [in C++03] other than just existing for completeness?

    Surprisingly, yes. C++ design criteria included a high degree of backward compatibility with C. C had this keyword and there was no real reason to ban it or redefine its meaning in C++. So, the purpose was one less incompatibility with C.

    Does this keyword have any purpose in C other than just existing for completeness?

    I learned one only recently: ease of porting of ancient programs from B. C evolved from a language called B whose syntax was quite similar to that of C. However, B had no types whatsoever. The only way to declare a variable in B was to specify its storage type (auto or extern). Like this:

    auto i;

    This syntax still works in C and is equivalent to

    int i;

    because in C, the storage class defaults to auto, and the type defaults to int. I guess that every single program that originated in B and was ported to C was literally full of auto variables at that time.

    C++03 no longer allows the C style implicit int, but it preserved the no-longer-exactly-useful auto keyword because unlike the implicit int, it wasn't known to cause any trouble in the syntax of C.

提交回复
热议问题