G ++ does not compile C ++ 0x for loop

I experimented with some new C ++ 0x features with g ++. Lambdas, auto , and other new features worked like a charm, but the for-loop could not be compiled. This is the program I tested:

 #include <iostream> #include <vector> int main () { std::vector<int> data = { 1, 2, 3, 4 }; for ( int datum : data ) { std::cout << datum << std::endl; } } 

I compiled it with

 g++ test.cpp -std=c++0x 

I also tried gnu++0x , but the result was the same.

This was the result:

 test.cpp: In function 'int main()': test.cpp:8:21: error: expected initializer before ':' token test.cpp:12:1: error: expected primary-expression before '}' token test.cpp:12:1: error: expected ';' before '}' token test.cpp:12:1: error: expected primary-expression before '}' token test.cpp:12:1: error: expected ')' before '}' token test.cpp:12:1: error: expected primary-expression before '}' token test.cpp:12:1: error: expected ';' before '}' token 

Thanks in advance for your help.

EDIT: I am using GCC version 4.5.2, which I see is too old.

+6
source share
1 answer

You need GCC 4.6 and higher to get ranges for loops.

GCC status C ++ 0x

 $ cat for.cpp #include <iostream> int main() { for (char c: "Hello, world!") std::cout << c; std::cout << std::endl; return 0; } $ g++ -std=c++0x -o for for.cpp $ ./for Hello, world! $ g++ --version g++ (GCC) 4.6.1 20110325 (prerelease) 
+14
source

Source: https://habr.com/ru/post/895094/


All Articles