Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

G++ doesn't compile C++0x range-based for loop

Tags:

c++

c++11

g++

I was experimenting with some of the new C++0x features with G++. Lambdas, auto, and the other new features worked like a charm, but the range-based for-loop failed to compile. This is the program I was testing:

#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 output was the same.

This was the output:

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 now see is too old.

like image 478
rovaughn Avatar asked Aug 15 '11 21:08

rovaughn


1 Answers

You need GCC 4.6 and above to get range-based for loops.

GCC's C++0x status

$ 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)
like image 66
Peter Alexander Avatar answered Oct 29 '22 02:10

Peter Alexander