3

I am completely new to C++ and I am now following the C++ Primer book.

I wrote a small example about strings, here is the code:

#include <iostream>
#include <string>
#include <cctype>

using std::cin;
using std::cout;
using std::endl;
using std::string;

int main() {
    string s("Hello World");

    for (auto &c : s)
        c = toupper(c);

    cout << s << endl;

    return 0;
}

I am on Linux with GCC version 4.4.6 and I tried to compile this code with:

g++ test_strings.c -std=c++0x

but got the following errors:

test_strings.c: In function 'int main()':
test_strings.c:14: error: expected initializer before ':' token
test_strings.c:19: error: expected primary-expression before 'return'
test_strings.c:19: error: expected ')' before 'return'

I copied the program from the textbook, so I though it was a misspelling but after a check and trying searching on the web and updating my gcc the error reminds. Help will be greatly appreciated, thanks in advance.

ildjarn
  • 62,044
  • 9
  • 127
  • 211
Supa Mario
  • 31
  • 1
  • 2
  • 4
    http://stackoverflow.com/questions/5032435/new-c11-range-for-foreach-syntax-which-compilers-support-it Use g++ 4.6 – ta.speot.is Jan 02 '13 at 06:47
  • 2
    why does your c++ source file have a C extension? – nurettin Jan 02 '13 at 06:50
  • 1
    … the `.c` extension will cause some compilers to actually misidentify the file's language. – Potatoswatter Jan 02 '13 at 08:04
  • `g++ foo.c` appears to treat the file as C++ -- but it's definitely poor practice to use the `.c` suffix for a C++ source file. `.cpp` is most common. (I've also seen `.C`, but that can cause confusion on case-insensitive file systems.) – Keith Thompson Jan 08 '13 at 21:06

1 Answers1

5

As per the C++0x/C++11 Support in GCC page, you need to be running gcc 4.6 to get the range-for feature.

The 4.6 changes page contains:

Improved experimental support for the upcoming C++0x ISO C++ standard, including support for constexpr (thanks to Gabriel Dos Reis and Jason Merrill), nullptr (thanks to Magnus Fromreide), noexcept, unrestricted unions, range-based for loops (thanks to Rodrigo Rivas Costa), opaque enum declarations (thanks also to Rodrigo), implicitly deleted functions and implicit move constructors.

Since you're running gcc 4.4.6, it's not available to you.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953