Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Range-based for loop with initializer

Use case

Limit scope of loop variable.

Explanation

Like C++17 if with initializer, but for range-based for loops.

Code

#include <cstdint>
#include <iostream>
#include <vector>

int main() {
  for (std::vector<uint64_t> addrs{0x1000, 0x1100, 0x1200}; auto addr : addrs) {
    std::cout << "0x" << std::hex << addr << "\n";
  }
  return 0;
}

View on GitHub.

Output

$ ./src/c++20/build/range-based-for-loop-with-initializer
0x1000
0x1100
0x1200