I have a simple function which counts the letter t in a string:
#include <stdio.h>
#include <string.h>
static int count_t_letters(const char *t) {
int r;
r = 0;
while(*t) {
if(*t == 't') {
++r;
}
++t;
}
return r;
}
int main() {
printf("%i", count_t_letters("test"));
}
here's the optimization I was expecting:
int main() {
printf("%i", 2);
}
Why is this simple function not optimized like I expected in neither gcc nor clang? (godbolt)
What I figured out so far:
++t
after the if
(godbolt)Because you're creating side effects by modifying the pointer.
If instead of incrementing t
you simply use a normal index int and increment that instead, then gcc has no trouble optimizing it as you desire.
Modifying the pointer has side effects.
Another way, simply make a copy of the pointer, and modify the copy. Again it optimizes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With