Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

c++ - Why do I need to explicitly write the 'auto' keyword?

I am moving towards C++11 from C++98 and have become familiar with the auto keyword. I was wondering why we need to explicitly declare auto if the compiler is able to automatically deduce the type. I know C++ is a strongly typed language and this is a rule but was it not possible to achieve the same outcome without explicitly declaring a variable auto?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Dropping the explicit auto would break the language:

e.g.

int main()
{
    int n;
    {
        auto n = 0; // this shadows the outer n.
    }
}

where you can see that dropping the auto would not shadow the outer n.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...