error: expected initializer before ‘:’ token

16,538

Your compiler is too old to support range-based for syntax. According to GNU it was first supported in GCC 4.6. GCC also requires you to explicitly request C++11 support, by giving the command-line option -std=c++11, or c++0x on compilers as old as yours.

If you can't upgrade, then you'll need the old-school equivalent:

for (auto it = inNwsFile.begin(); it != inNwsFile.end(); ++it) {
    std::string const &nwFile = *it; // const needed because inNwsFile is const
    //some...
}

I believe auto is available in GCC 4.4 (as long as you enable C++0x support), to save you writing std::vector<string>::const_iterator.

If you really do need a non-const reference to the vector's elements then, whichever style of loop you use, you'll need to remove the const from the function parameter.

Share:
16,538
Aslan986
Author by

Aslan986

Updated on June 04, 2022

Comments

  • Aslan986
    Aslan986 almost 2 years

    I am trying to compile some C++ code (which can be compiled with Visual Studio 2012 on Windows) with g++-4.4.

    I have this snippet of code,

    const std::string cnw::restoreSession(const std::vector<string> &inNwsFile) {
       for (std::string &nwFile : inNwsFile){
           // some...
       }
    }
    

    that I cannot compile because of this error:

    CNWController.cpp:154: error: expected initializer before ‘:’ token
    

    Can you give me some advise on how to solve this problem?