Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 402
Jan Jongboom Avatar asked Dec 09 '25 10:12

Jan Jongboom


2 Answers

The compiler does eliminate the else path in the inlined function in main. You're confusing the global function that is not called anyway and will be discarded by the linker eventually.

If you use the -fwhole-program flag to let the compiler know that no other file is going to be linked, that unused segment is discarded:

[See online]

Enter image description here

Additionally, you use static or inline keywords to achieve something similar.

like image 197
Ayxan Haqverdili Avatar answered Dec 12 '25 01:12

Ayxan Haqverdili


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.

like image 41
MrTux Avatar answered Dec 12 '25 01:12

MrTux



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!