Question

Weird behaviour with 'if constexpr' and templates in MSVC

The code below behaves incorrectly.

When f<0> or f<5> is called, it prints as if k = true, but the if statement behaves as if k = false. When f<1> is called, it does the opposite.

The bug does not appear without templates, constexpr, or the negator(!). It can be removed by having a separate variable (see below). I'm assuming this has something to do with how MSVC deals with templates?

#include <stdio.h>

const bool k = false;

template<int n>
void f()
{
    printf("%d %d\n", k, n); //prints 1 0 or 1 5 when calling f<0> or f<5>, respectively
    //kop = !k 
    if constexpr(!k)//if constexpr(kop) works fine
    {
        //doesn't enter the conditional when calling f<1>
        int f = 9;
        printf("%d %d\n", f, n); 
    }
}

int main()
{
    f<0>();
    f<1>();
    f<1>();
    f<5>();
}
 8  129  8
1 Jan 1970