Is it possible to declare two variables of different types in the initialization body of a for loop in C++?
For example:
for(int i=0,j=0 ...
defines two integers. Can I define an int
and a char
in the initialization body? How would this be done?
Not possible, but you can do:
Or, explicitly limit the scope of
f
andi
using additional brackets:Define a macro:
Just remember, your variable scopes will not be within the for loop this way either.
C++17: You should use a structured binding declaration. The syntax is supported in gcc-7 and clang-4.0 (clang live example). This allows us to unpack a tuple like so:
C++14: You can do the same as C++11 (below) with the addition of type-based
std::get
. So instead ofstd::get<0>(t)
in the below example, you can havestd::get<int>(t)
.C++11:
std::make_pair
allows you to do this, as well asstd::make_tuple
for more than two objects.std::make_pair
will return the two arguments in astd::pair
. The elements can be accessed with.first
and.second
.For more than two objects, you'll need to use a
std::tuple
std::make_tuple
is a variadic template that will construct a tuple of any number of arguments (with some technical limitations of course). The elements can be accessed by index withstd::get<INDEX>(tuple_object)
Within the for loop bodies you can easily alias the objects, though you still need to use
.first
orstd::get
for the for loop condition and update expressionC++98 and C++03 You can explicitly name the types of a
std::pair
. There is no standard way to generalize this to more than two types though:You can't declare multiple types in the initialization, but you can assign to multiple types E.G.
Just declare them in their own scope.
No - but technically there is a work-around (not that i'd actually use it unless forced to):
See "Is there a way to define variables of two types in for loop?" for another way involving nesting multiple for loops. The advantage of the other way over Georg's "struct trick" is that it (1) allows you to have a mixture of static and non-static local variables and (2) it allows you to have non-copyable variables. The downside is that it is far less readable and may be less efficient.