Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiler differences for use of strcmp in a constexpr

The following compiles in GCC but not in Clang:

#include <cstring>

constexpr int test = strcmp("test", "test");

So my question is, how does GCC handle strcmp differently to make this possible? Is strcmp some type of builtin, or does its standard library have a non-standard definition of strcmp that includes constexpr?

like image 619
Chris_F Avatar asked Jul 01 '14 23:07

Chris_F


2 Answers

The code compiles on gcc because it provides a built-in version of strcmp that is evaluated at compile time, assuming you pass string literals to the function.

gcc will reject the code if you pass the -fno-builtin (or -fno-builtin-strcmp) flag.

like image 151
Praetorian Avatar answered Nov 12 '22 14:11

Praetorian


Nothing forbids a function from being constexpr. There's just no guarantee that strcmp is constexpr. A good compiler will probably be able to perform string operations on compile-time constant strings efficiently, but that's an implementation detail.

like image 3
Kerrek SB Avatar answered Nov 12 '22 12:11

Kerrek SB