Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • Simple functions with integer pointer arguments are optimized to a constant (godbolt)
  • Using C++ with a constexpr enables this optimization (godbolt)
  • Clang is able to do such an optimization if there is no ++t after the if (godbolt)
like image 548
Julius Avatar asked Dec 31 '18 15:12

Julius


1 Answers

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.

like image 51
RubyPanther Avatar answered Oct 10 '22 09:10

RubyPanther