I have the following two functions which do basically the same:
enum Direction{
N = 0,
NW,
W,
SW,
S,
SE,
E,
NE,
TOTAL_DIRS
};
char const * const strings[] = {"N", "NW", "W", "SW", "S", "SE", "E", "NE"};
char const *
getDirString2(unsigned dir) {
if (TOTAL_DIRS > dir)
return strings[dir];
return nullptr;
}
char const *
getDirString3(unsigned dir) {
char const * const strings[] = {"N", "NW", "W", "SW", "S", "SE", "E", "NE"};
if (TOTAL_DIRS > dir)
return strings[dir];
return nullptr;
}
But while g++ optimizes the function which uses the global array like I would expect. It creates much more, convoluted code for the alternative. Clang creates the same code for both and if I use a switch-statement instead, both clang and c++ also create the same code as for getDirString2
.
Here is a link to compiler explorer https://godbolt.org/z/GxvrTv
Is this something for which I should file a bug report for g++ or is there a good reason for that?