liveBook · Manning

If statement with initializer

As explained in Learn C++ by Example

An if statement with an initializer combines a local initialization and a conditional test in one statement, limiting the initialized name's scope to the statement.

An if statement with an initializer combines a local initialization and a condition: if (init; condition). The initialized name remains in scope only within the statement, keeping related checks together. section 3.3.4

Checking for a misplaced digit

A number-guessing game can search for a guessed digit and test the returned position in one statement: if (size_t idx = ns.find(guess_char, 0); idx != std::string::npos). When the digit is found, the code marks it as misplaced and consumes that position. section 3.3.4

Without the initializer form, the index would be declared and checked in separate statements. Both approaches work, but the initializer form keeps the temporary index local to the conditional logic. section 3.3.4

if (size_t idx = ns.find(guess_char, 0); idx != std::string::npos)

Inspect the compact form used to find a digit and test whether the search succeeded. section 3.3.4

How Learn C++ by Example covers it

How deep it goes
Defines the syntax, compares separate statements, and explains limited scope without descending into language internals.
Examples
Demonstrates digit searching, misplaced-digit markers, and assertions in a number-guessing game.
What you can do after
Apply the C++17 syntax to keep temporary variables local to conditional checks.
How it connects
Links conditional statements with std::string::find, string positions, and variable scope.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn C++ by Example. The section links point to the parts of the book it draws on.