Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Comments on Why is the new auto keyword from C++11 or C23 dangerous?
Post
Why is the new auto keyword from C++11 or C23 dangerous?
In older C and C++ standards, the auto
keyword simply meant automatic storage duration. As in the compiler automatically handles where the variable is stored, typically on the stack or in a register. And it was a pretty useless keyword since it can only be used at local scope, where all variables default to automatic storage duration anyway.
The C++11 committee decided to change the meaning of this keyword so that during declaration, the type is picked based on the initializer(s) provided. For example auto i=0;
will result in int
because the integer constant 0
is of type int
.
As I understand it, the main rationale was to get rid of cumbersome declarations in for
loops in particular.
for(auto i = cont.begin(); ...
is admittedly easier for the eye than
for(std::vector<std::string>::iterator i = cont.begin(); ...
However, veteran programmers seem to raise concerns about auto
being unsafe. It seems to be a topic where there's plenty of personal opinions as seen over at SO: How much is too much with C++11 auto keyword? Some people just happily encourage "go for it everywhere". Others, including various well-known C++ gurus, speak in favour of using it with caution.
Now C too is adapting the same functionality of auto
as C++,
as per C23.
What exactly is dangerous with the auto
keyword?
1 comment thread