Joe Kessler
Joe Kessler

Reputation: 51

Can C++ Compilers optimize overloaded default parameters?

I've been refactoring a codebase for an embedded chip that uses a lot of convenient overloaded functions with default parameters, like this:

int state, prevState;
float time;

void setState(int newState, float newtime)
{
    if (newState != state)
    {
        prevState = state;
        time = newTime;
    }
    state = newState;
}

inline void setState(int newState) 
{
    setState(newState, time);
}

In its current implementation, the second function is manually optimized:

void setState(int newState) 
{
    if (newState != state)
        prevState = state;
    state = newState;
}

If I use the new implementation (the one with inline) is there a way for the compiler to recognize and remove the code involving time, or is the old manual way the best practice?

I've used Godbolt's compiler on GCC yet can't find an appropriate setting for code or a compile flag that doesn't obfuscate everything, or have the calls remain.

Upvotes: 0

Views: 93

Answers (1)

Chronial
Chronial

Reputation: 70773

GCC generates exactly the same code for both variants with -O3: godbolt.

Note the the inline keyword is at best only considered as a suggestion in the compiler's decision regarding inlining. It's main effect is something completely different.

Upvotes: 1

Related Questions