Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

auto keyword strange behavior in C++11

Tags:

c++

c++11

Theoretical question only - why i can't write such code:

auto auto foo = 0;

First auto keyword - storage class specifier (yeah, i know that it's useless and deprecated in C++11), second auto keyword - auto type-specifier.

So what's wrong?

And again - i don't really want to use this in real code.

like image 373
FrozenHeart Avatar asked Aug 29 '12 17:08

FrozenHeart


People also ask

What is auto keyword in C ++ 11?

The auto keyword directs the compiler to use the initialization expression of a declared variable, or lambda expression parameter, to deduce its type.

Does C ++ 11 have auto?

C++11 introduces the keyword auto as a new type specifier. auto acts as a placeholder for a type to be deduced from the initializer expression of a variable. With auto type deduction enabled, you no longer need to specify a type while declaring a variable.

What does auto keyword do in C?

auto: This is the default storage class for all the variables declared inside a function or a block. Hence, the keyword auto is rarely used while writing programs in C language. Auto variables can be only accessed within the block/function they have been declared and not outside them (which defines their scope).

Should I use Auto everywhere?

Using auto all over the place will make your code less readable and harder to debug because you will have to deduce the types yourself while reading the code.


2 Answers

The auto storage class specifier is not "useless and deprecated in C++11," it has been removed entirely. The auto keyword is no longer a storage class specifier and cannot be used as one.

In C++11, auto is a simple type specifier.

like image 200
James McNellis Avatar answered Nov 01 '22 08:11

James McNellis


From the Stroustrup's FAQ:

....The old meaning of auto ("this is a local variable") is now illegal. Several committee members trawled through millions of lines of code finding only a handful of uses -- and most of those were in test suites or appeared to be bugs.

Which indicates there's much not code used using "auto" as storage specifier.

like image 32
P.P Avatar answered Nov 01 '22 07:11

P.P