Learning Hub Search Ctrl K

Modern C++ › C++17

if constexpr and if/switch Initializers

Compile-time branches and scoped init statements.

Since C++17 intermediate #if-constexpr#init-statements#switch#templates#compile-time-branching

Explanation

if constexpr (condition) is a compile-time if. The condition must be a constant expression, and the branch that is not taken is discarded (not instantiated). That allows code that would not compile for some types to live in the other branch, replacing most tag dispatch and SFINAE tricks.

if and switch with an initializer (if (init; condition)) declare a variable scoped to the statement. It keeps temporaries and iterators from leaking into the enclosing scope, and pairs well with structured bindings.

if (auto it = m.find(key); it != m.end()) { ... }   // 'it' lives only in the if/else

Example

#include <iostream>
#include <map>
#include <mutex>
#include <string>
#include <type_traits>
#include <vector>

template <typename T>
std::string describe(const T& v) {
    if constexpr (std::is_integral_v<T>) {
        return "integer " + std::to_string(v);
    } else if constexpr (std::is_floating_point_v<T>) {
        return "float " + std::to_string(v);
    } else {
        return "other: " + std::string(v);          // only compiled if T converts to string
    }
}

template <typename Container>
void addOne(Container& c) {
    if constexpr (std::is_same_v<Container, std::vector<int>>)
        c.push_back(1);
    else
        c.insert(1);                                // std::vector<int> has no insert(int): OK, it's discarded
}

std::mutex m;
int shared = 0;

int main() {
    std::cout << describe(42) << ", " << describe(2.5) << ", " << describe("hi") << "\n";

    std::map<std::string, int> ages{{"Ann", 30}, {"Bob", 25}};
    if (auto it = ages.find("Ann"); it != ages.end())          // init-statement
        std::cout << it->first << " " << it->second << "\n";
    // 'it' is out of scope here

    if (std::lock_guard<std::mutex> lock(m); shared == 0)      // lock held for the whole if/else
        shared = 1;

    switch (auto n = ages.size(); n) {                         // init-statement for switch
        case 0:  std::cout << "empty\n"; break;
        case 2:  std::cout << "two\n";   break;
        default: std::cout << n << "\n";
    }

    std::vector<int> v;
    addOne(v);
    std::cout << v.size() << "\n";
    return 0;
}

Common pitfalls

  • A plain if (not constexpr) still compiles both branches, so the “other type” code must be valid for every T.
  • The discarded branch of if constexpr is only discarded inside a template; in a normal function, both branches are still checked.
  • The condition must be a compile-time constant; runtime values are an error.
  • With a lock in the init-statement, the variable name must not be omitted (std::lock_guard<std::mutex>(m) would be a temporary that unlocks at once).
  • return types must still agree across non-discarded branches when the return type is deduced.

Legacy vs modern

C++11/14 needed overload sets with tag types (std::true_type/false_type), std::enable_if, or partial specialization to branch on types; the init-statement replaced extra braces { auto it = ...; if (...) {...} }. C++20 concepts and requires complement if constexpr; C++23 adds if consteval.

Exercises

1. Why can't you replace if constexpr with a normal if in describe above?

With a normal if, std::string(v) would still be compiled for int and double, which is an error. if constexpr discards the untaken branch at instantiation.