Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are constexpr evaluated on target platform?

Tags:

c++

constexpr

I wonder if, for example, evaluated compiled on a little endian platform will return true on a big endian target platform.

constexpr bool is_little_endian()
{
    int num = 1;
    return (1 == *(char *)&num);
}

In other words, are constexpr evaluated as if on the target?

EDIT: This example isn't correct, but the question is still active.

like image 500
FlashMcQueen Avatar asked Oct 16 '25 18:10

FlashMcQueen


1 Answers

First off: If you compile code for a given target, then the compiler will generate code for that target. This, of course, includes expressions that are evaluated at compile-time - otherwise every cross compilation that involved such expressions would be broken.

However, just marking a function as constexpr does not guarantee that it is evaluated at compile-time. In particular, your sample function cannot (according to the standard) be evaluated at compile-time, so it is orthogonal to the primary question.

As remarked in the comments, you can't really find out endianness at compile-time without querying the compiler directly. The compiler has to know (because it has to generate code) and any reasonable compiler will provide a way for you to query this information (at compile-time).

like image 121
Max Langhof Avatar answered Oct 19 '25 06:10

Max Langhof