0

Well, I tried it all. This should be very simple, yet I am stock at finding out what in the world is going on with my foreach. It just don't help.

    #include <QCoreApplication> 
    //coreapplication or Qapplication the error is there
    #include <QList>
    #include <QDebug>

    int main()
    {
      QList<int> list;

      list << 1 << 2 << 3 << 4 << 5;

      foreach (int i, list) //expected token ';' got 'int'.
      {
        qDebug() << i;
      }
    }
    /*
    QT += core gui

    TARGET = QtTest
    CONFIG += console
    CONFIG -= app_bundle
    CONFIG += no_keywords

    TEMPLATE = app

    SOURCES += main.cpp

    */
Jose L. Rico
  • 13
  • 1
  • 4

2 Answers2

11

You specified no_keywords in your config. You have to use Q_FOREACH instead of foreach. See the documentation for foreach.

That being said, I would switch to the C++11 range-based for, since it doesn't have issues with commas in types. For example,

Q_FOREACH (QPair<int, int> p, pairList)

won't compile since the preprocessor thinks you're trying to invoke the macro with 3 arguments instead of 2.

Daniel Gallagher
  • 6,915
  • 25
  • 31
  • 1
    One can work around the comma issue with a typedef, but yes, range-based for is to be preferred if one can use it. – Frank Osterfeld Nov 13 '15 at 18:40
  • Interestingly enough im getting the same error but I have the correct project configuration. Not only that, foreach works on Qt containers but not an array containing a primitive type like int – Dean P May 15 '19 at 11:45
4

Instead you can use the C++11 for(:):

for(int i:list)
{
    qDebug() << i;
}

Note that you will have to compile with the C++-11 flag, therefore add this line to your project file:

QMAKE_CXXFLAGS += -std=c++11

Note that the C++11 for is more efficient than the Qt foreach as indicated by: Qt foreach loop ordering vs. for loop for QList


Edit: Like commented by Frank Osterfeld you can also use:

CONFIG+=c++11

in your .pro file since Qt 5.4 as commented here: How to use C++11 in your Qt Projects.

Community
  • 1
  • 1
agold
  • 6,140
  • 9
  • 38
  • 54