Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constexpr: Comparision to nullptr - Bug or feature?

GCC is unable to evaluate some expression as constant. Clang however is nice with it.

/*
 */
constexpr int foo(const int * array)
{
  if (array == nullptr) // Error: '(((const int*)(& array)) == 0u)' is not a constant expression
  {
    return 0;
  }

  return 1;
}

constexpr int bar()
{
  int array[100] = {};

  return foo(array);
}

static_assert(bar() == 1, "outch..."); // Does not compile. See above.
static_assert(foo(nullptr) == 0, "okay");

constexpr int i[100] = {};
static_assert(foo(i) == 1, "okay");

Does also not work:

constexpr int foobar()
{
  int array[100] = {};
  int *ar = array;
  if (ar == nullptr) // Error...
  {
    return 0;
  }
  return 1;
}

static_assert(foobar() == 1, "okay");

Same thing:

constexpr int foo2()
{ 
  int *a = nullptr;
  if (a == nullptr) // Error...
  {
    return 0;
  } 
  return 1;
}

static_assert(foo2() == 0, "okay");

Live Example

I mean, a comparison to nullptr should be something else than a comparison to an other random address.

Would you say: it is a bug or a matter of interpretation? For me, it is difficult to write the same code for both compilers...

This error happens for GCC 5.0 to 5.4. In GCC 6+ only foobar() does not compile.

like image 497
Viatorus Avatar asked Sep 09 '16 06:09

Viatorus


1 Answers

This is already fixed for gcc-7. I've opened: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77539 to request a backport.

like image 169
octoploid Avatar answered Oct 08 '22 00:10

octoploid