Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope of variables declared inside `if constexpr` blocks

Is that ill-formed or is just the compiler (g++-7 in my case) is just still buggy? because it says that n is not defined.

template<class T>
auto tup(T const& t)
{
    if constexpr(hana::length(t)() % 2)
        auto n = hana::append(t, nullptr);
    else
        auto const& n = t;

    return n;
}

int main()
{
   std::cout << hana::length(tup(std::tuple(3, "h", 'c'))) << '\n';
}

n will be always defined, no matter for which branch will the compiler go.

like image 678
Peregring-lk Avatar asked Oct 19 '25 16:10

Peregring-lk


2 Answers

Your program is ill-formed because each n is restricted to the scope of the single statement declaring it.

C++17 draft N4659 [stmt.select]/1 says:

The substatement in a selection-statement (each substatement, in the else form of the if statement) implicitly defines a block scope ([basic.scope]). If the substatement in a selection-statement is a single statement and not a compound-statement, it is as if it was rewritten to be a compound statement containing the original substatement. [ Example:

if (x)
  int i;

can be equivalently rewritten as

if (x) {
  int i;
}

Thus after the if statement, i is no longer in scope. - end example ]

This rule applies to all for, while, switch, and if statements - whether or not the constexpr keyword is used with if.

like image 80
aschepler Avatar answered Oct 21 '25 04:10

aschepler


constexpr change nothing in this case.

It's exactly like in this example

int foo (int a)
 {
   if ( a == 0 )
    {
      int r = 0;
    }
   else
    {
      int r = 0;
    }

   return r;
 }

r is defined in both cases. And with the same value.

But the scope of r is limited to the if and don't reach the return.

If you can solve the problem returning immediatly; I mean

template<class T>
auto tup(T const& t)
{
    if constexpr(hana::length(t)() % 2)
        return hana::append(t, nullptr);
    else
        return t;
}
like image 31
max66 Avatar answered Oct 21 '25 06:10

max66