C++, more than one declaration in for loop initialization expression

Question:

Is there a way in C++ to declare multiple variables of different types in a for loop initialization expression?

For instance:

for (size_t s = 0, float f = 0.f; ; ) {}

Answer:

Since C++17 you have an option with structured binding

for (auto [s, f] = std::make_tuple(0, 0.0); ; ) 
{
  // Работаем с `s` и `f`
}

And before the advent of structured binding, there were only tricks like

for (struct { size_t s = 0; float f = 0.f; } sf; ; ) 
{ 
  // Работаем с `sf.s` и `sf.f`
}

or

for (struct { size_t s; float f; } sf = { 0 }; ; )
{ 
  // Работаем с `sf.s` и `sf.f`
}

This trick is not widely used, but has been available since S.

Scroll to Top