Roger Luo
Roger Luo

Reputation: 355

why i cannot use the auto keyword in the last version of gcc

All, recently i tried to use the new features supported by c++11, and i wrote such statement however the compiler ran failed.

auto x = 1;

the report error listed below:

D:\DEV\CBCppTest\main.cpp||In function 'int main()':|
D:\DEV\CBCppTest\main.cpp|22|warning: 'auto' changes meaning in C++11; please remove it [-Wc++0x-compat]|
D:\DEV\CBCppTest\main.cpp|22|error: 'x' does not name a type|
||=== Build finished: 1 errors, 1 warnings ===|

Why the last gcc version 4.7.0 on MinGW cannot support the this statement. But the compiler of vs10 passed. Could anyone know the reason for this issue?

Upvotes: 23

Views: 30943

Answers (5)

arm
arm

Reputation: 117

For me adding "-std=c++0x"" to g++ command line fixed the issue.

Upvotes: 1

leftaroundabout
leftaroundabout

Reputation: 120711

To explain what the compiler is actually complaining about: auto used to be an old C keyword, declaring that this variable has automatic storage. These keywords have little to do with the type system, they specify how variable are represented in memory: where they're stored (processor register vs. main memory / stack) and how the memory is reclaimed. auto means the variable is stored on the stack (though the processor may optimise it into a processor register) and the memory is automatically reclaimed when the variable goes out of scope – which is the right choice in almost any situation1 and thus the default, so virtually nobody ever used this old auto keyword. Yet C++03 still provided backwards compatibility for code that has it; today's compilers still want to support legacy code.


1Though often you want objects to reside on the heap, you'll still be accessing those through variables on the stack; C++ has its own methods of using heap-allocated memory (new, std::vector etc.), you don't need the unsafe C-style malloc stuff.

Upvotes: 9

Raj
Raj

Reputation: 21

This is due to the feature not being enable by default by the GCC compiler. If you're on Codeblocks, go to Settings --> Compiler and enable the feature as shown - https://i.sstatic.net/e4Wq6.jpg

Upvotes: 2

Johan Kotlinski
Johan Kotlinski

Reputation: 25739

When compiling, you need to add -std=c++11 to g++ command line.

Upvotes: 8

dexametason
dexametason

Reputation: 1133

"GCC provides experimental support for the 2011 ISO C++ standard. This support can be enabled with the -std=c++11 or -std=gnu++11 compiler options; the former disables GNU extension."

It comes from here: c+11 support

Upvotes: 33

Related Questions