Answer the question
In order to leave comments, you need to log in
Why does clang (x86-64 7.0.0) generate worse code (in this example)?
Hello!
I'm learning C, reading books a little, and learning how standard library functions work. Then I try to implement them myself. I use the cppreference site and the libc-OpenBSD sources when I want to compare my code or see how it's done there, I use the godbolt Compiler Exlorer for comparison.
So, I wrote the following code for the standard strrchr function:
char *strrchr(char const *beg, int chr)
{
char const *fnd;
for (fnd = NULL; *beg != '\0'; ++beg)
if (*beg == (char)chr)
fnd = beg;
return (char *)fnd;
}
char *strrchr(char const *beg, int chr)
{
char const *fnd;
for (fnd = NULL;; ++beg) {
if (*beg == (char)chr)
fnd = beg;
if (*beg == '\0')
return (char *)fnd;
}
}
Answer the question
In order to leave comments, you need to log in
Look at the assembler that the compiler produces.
The compiler does not always guess to optimize.
It looks like they have fewer conditional jumps, and your code is written in such a way that the compiler will not come up with an optimization for it.
They have 2 if'a will become one conditional transition. You have - 1 if it will become.
In the loop, you have more checks, the compiler does not guess to take out the brackets - it does not learn like a neural network or a person.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question