Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error compilation with constexpr

I'm trying to compile this code:

enum class Order : char
{
    Little,
    Big
};

constexpr Order get_order() {
    uint16_t x = 1;
    return *((uint8_t *) &x) == 0 ? Order::Big : Order::Little;
}

I do it with -std=c++14 flag but i get that error:

In function ‘constexpr byteorder::Order byteorder::get_order()’: /home/user/dev/c++/render/include/byteorder.h:19:1: error: body of constexpr function ‘constexpr byteorder::Order byteorder::get_order()’ not a return-statement

It looks like c++11 !

How could it happen if c++14 allows local variables in constexpr functions?

Debian Jessie, gcc 4.9.2

like image 324
vlad4378 Avatar asked Dec 19 '22 14:12

vlad4378


1 Answers

clang says:

test.cpp:9:17: error: constexpr function never produces a constant expression
    [-Winvalid-constexpr]
constexpr Order get_order() {
                ^
test.cpp:11:14: note: cast that performs the conversions of a reinterpret_cast
is not allowed in a constant expression
    return *((uint8_t *) &x) == 0 ? Order::Big : Order::Little;
             ^
1 error generated.
like image 193
Howard Hinnant Avatar answered Dec 24 '22 01:12

Howard Hinnant