Julius
Julius

Reputation: 1265

Why is this call to a pure function with a string literal argument not optimized to a constant value?

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:

Upvotes: 8

Views: 352

Answers (1)

RubyPanther
RubyPanther

Reputation: 31

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.

Upvotes: 1

Related Questions