Why doesn't this “undefined extern variable” result in a linker error in C++17?

前端 未结 4 1004
后悔当初
后悔当初 2021-02-05 00:43

I have compiled and ran the following program in a C++17 compiler (Coliru). In the program, I declared an extern variable, but did not defi

4条回答
  •  别跟我提以往
    2021-02-05 01:38

    This has alrady been answered, but if you are interested, cppreference.com has exactly this example for constexpr if:

    Constexpr If

    The statement that begins with if constexpr is known as the constexpr if statement.

    In a constexpr if statement, the value of condition must be a contextually converted constant expression of type bool. If the value is true, then statement-false is discarded (if present), otherwise, statement-true is discarded.
    [...]
    The discarded statement can odr-use a variable that is not defined:

    extern int x; // no definition of x required
    int f() {
    if constexpr (true)
        return 0;
    else if (x)
        return x;
    else
        return -x;
    }
    

提交回复
热议问题