Wednesday, August 31, 2022

[SOLVED] For a function that takes a const struct, does the compiler not optimize the function body?

Issue

I have the following piece of code:

#include <stdio.h>

typedef struct {
    bool some_var;
} model_t;

const model_t model = {
    true
};

void bla(const model_t *m) {
    if (m->some_var) {
        printf("Some var is true!\n");
    }
    else {
        printf("Some var is false!\n");
    }
}

int main() {
    bla(&model);
}

I'd imagine that the compiler has all the information required to eliminate the else clause in the bla() function. The only code path that calls the function comes from main, and it takes in const model_t, so it should be able to figure out that that code path is not being used. However:

Without inline

With GCC 12.2 we see that the second part is linked in.

If I inline the function this goes away though:

With inline

What am I missing here? And is there some way I can make the compiler do some smarter work? This happens in both C and C++ with -O3 and -Os.


Solution

The compiler cannot optimize the else path away as the object file might be linked against any other code. This would be different if the function would be static or you use whole program optimization.



Answered By - MrTux
Answer Checked By - Pedro (WPSolving Volunteer)