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

Selection statements with initializer

Use case

Limit variable scope in conditionals.

Explanation

if (init; condition) declares variables scoped to the if/else block.

Code

#include <cstdint>
#include <iostream>
#include <map>

int main() {
  std::map<uint64_t, const char *> symbols{{0x10001000, "_main"}};

  if (auto it = symbols.find(0x10001000); it != symbols.end()) {
    std::cout << "Found: " << it->second << "\n";
  }

  return 0;
}

View on GitHub.

Output

$ ./src/c++17/build/selection-statements-with-initializer
Found: _main