Qt's foreach Keyword

The foreach Keyword

Note: The foreach keyword was introduced before the C++11 range-based loops existed. New code should prefer C++11 range-based loops.

The foreach keyword is a Qt-specific addition to the C++ language, and is implemented using the preprocessor.

Its syntax is: foreach (variable, container) statement. For example, here's how to use foreach to iterate over a QList<QString>:

 QList<QString> values;
 ...
 QString str;
 foreach (str, values)
     qDebug() << str;

The foreach code is significantly shorter than the equivalent code that uses iterators:

 QList<QString> values;
 ...
 QListIterator<QString> i(values);
 while (i.hasNext()) {
     QString s = i.next();
     qDebug() << s;
 }

Unless the data type contains a comma (e.g., std::pair<int, int>), the variable used for iteration can be defined within the foreach statement:

 QList<QString> values;
 ...
 foreach (const QString &str, values)
     qDebug() << str;

And like any other C++ loop construct, you can use braces around the body of a foreach loop, and you can use break to leave the loop:

 QList<QString> values;
 ...
 foreach (const QString &str, values) {
     if (str.isEmpty())
         break;
     qDebug() << str;
 }

With QMap and QHash, foreach accesses the value component of the (key, value) pairs automatically, so you should not call values() on the container (it would generate an unnecessary copy, see below). If you want to iterate over both the keys and the values, you can use iterators (which are faster), or you can obtain the keys, and use them to get the values too:

 QMap<QString, int> map;
 ...
 foreach (const QString &str, map.keys())
     qDebug() << str << ':' << map.value(str);

For a multi-valued map:

 QMultiMap<QString, int> map;
 ...
 foreach (const QString &str, map.uniqueKeys()) {
     foreach (int i, map.values(str))
         qDebug() << str << ':' << i;
 }

Qt automatically takes a copy of the container when it enters a foreach loop. If you modify the container as you are iterating, that won't affect the loop. (If you do not modify the container, the copy still takes place, but thanks to implicit sharing copying a container is very fast.)

Since foreach creates a copy of the container, using a non-const reference for the variable does not allow you to modify the original container. It only affects the copy, which is probably not what you want.

An alternative to Qt's foreach loop is the range-based for that is part of C++11 and newer. However, keep in mind that the range-based for might force a Qt container to detach, whereas foreach would not. But using foreach always copies the container, which is usually not cheap for STL containers. If in doubt, prefer foreach for Qt containers, and range based for for STL ones.

You can remove the availability of the Qt's foreach loop by defining the QT_NO_FOREACH macro.