1// Copyright (C) 2020 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
5 \page foreach-keyword.html
6 \title Qt's foreach Keyword
8 \ingroup qt-basic-concepts
10 \brief Qt's foreach keyword.
14 \target foreach-keyword
15 \section1 The foreach Keyword
17 \note The foreach keyword was introduced before the C++11 range-based loops
18 existed. New code should prefer C++11 range-based loops.
20 The \c foreach keyword is a Qt-specific addition to the C++ language,
21 and is implemented using the preprocessor.
23 Its syntax is: \c foreach (\e variable, \e container) \e
24 statement. For example, here's how to use \c foreach to iterate
25 over a QList<QString>:
27 \snippet code/doc_src_containers.cpp 15
29 The \c foreach code is significantly shorter than the equivalent
30 code that uses iterators:
32 \snippet code/doc_src_containers.cpp 16
34 Unless the data type contains a comma (e.g., \c{QPair<int,
35 int>}), the variable used for iteration can be defined within the
38 \snippet code/doc_src_containers.cpp 17
40 And like any other C++ loop construct, you can use braces around
41 the body of a \c foreach loop, and you can use \c break to leave
44 \snippet code/doc_src_containers.cpp 18
46 With QMap and QHash, \c foreach accesses the value component of
47 the (key, value) pairs automatically, so you should not call
48 values() on the container (it would generate an unnecessary copy,
49 see below). If you want to iterate over both the keys and the
50 values, you can use iterators (which are faster), or you can
51 obtain the keys, and use them to get the values too:
53 \snippet code/doc_src_containers.cpp 19
55 For a multi-valued map:
57 \snippet code/doc_src_containers.cpp 20
59 Qt automatically takes a copy of the container when it enters a
60 \c foreach loop. If you modify the container as you are
61 iterating, that won't affect the loop. (If you do not modify the
62 container, the copy still takes place, but thanks to \l{implicit
63 sharing} copying a container is very fast.)
65 Since foreach creates a copy of the container, using a non-const
66 reference for the variable does not allow you to modify the original
67 container. It only affects the copy, which is probably not what you
70 An alternative to Qt's \c foreach loop is the range-based \c for that is
71 part of C++11 and newer. However, keep in mind that the range-based
72 \c for might force a Qt container to \l{Implicit Sharing}{detach}, whereas
73 \c foreach would not. But using \c foreach always copies the container,
74 which is usually not cheap for STL containers. If in doubt, prefer
75 \c foreach for Qt containers, and range based \c for for STL ones.