2
//code1
class Test {
public:
  constexpr Test(const char *p) : p_(p) {}
  constexpr int foo() const 
  {
    if(p_[0] != 'a')
      return 1;
    else
      return 2;
  }
  const char *p_;
};

int arr[Test("bbb").foo()];  //this works

why the following code not work?

  //code2
  constexpr int foo() const 
  {
    constexpr if (p_[0] != 'a') //add constexpr
      return 1;
    else
      return 2;
  }

Got an error:

error: expected unqualified-id before ‘if’

To my understanding, since "p_[0] != 'a'" can be evaluated at compile time(as shown in code1), so constexpr if (p_[0] != 'a') should be a valid statement which can be evaluate during compiling.

melpomene
  • 81,915
  • 7
  • 76
  • 137
camino
  • 9,449
  • 19
  • 60
  • 105
  • 2
    Pretend that you are a compiler. Can you compute what the value of the expression `p_[0] != 'a'` is? Full stop. Do not pass "Go". Do not collect $200 until you prove what the value of this expression is. At compile time. So you can replace that entire expression with a single value, and it has to be either true, or false. Unless you can answer this question this cannot be a `constexpr`. Because that's what it is, by definition. A constant expression. A constant. The End. – Sam Varshavchik Sep 15 '18 at 01:03
  • 4
    Syntax error, it must be `if constexpr`, not `constexpr if`! – Aconcagua Sep 15 '18 at 01:07
  • @barry Actually that isn't bad. The one that works, you can map it to `2` at compile time. The one that does not, if you say "well `false`", then replace the condition *with* `false`, you can quickly see how that isn't right. – Yakk - Adam Nevraumont Sep 15 '18 at 04:23

1 Answers1

2

To my understanding, since "p_[0] != 'a'" can be evaluated at compile time(as shown in code1), so constexpr if (p_[0] != 'a') should be a valid statement which can be evaluate during compiling.

p_[0] != 'a' can be evaluated compile-time but can also be evaluated run-time.

The problem is that a if constexpr test must be evaluated compile-time. And this is impossible when foo() is executed run-time or when the corresponding Test object is initialized run-time.

So the error.

Or better: the error if you write correctly

if constexpr (p_[0] != 'a')

In your case the order between if and constexpr is also wrong.

max66
  • 63,246
  • 10
  • 70
  • 107