Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Would the following code be optimized to one function call?

I have very little (read no) compiler expertise, and was wondering if the following code snippet would automatically be optimized by a relatively recent (VS2008+/GCC 4.3+) compiler:

Object objectPtr = getPtrSomehow();

if (objectPtr->getValue() == something1)       // call 1
    dosomething1;
else if (objectPtr->getValue() == something2)  // call N (there are a few more)
    dosomething2;

return;

where getValue() simply returns a member variable that is one of an enum. (The call has no observable effect)

My coding style would be to make one call before the "switch" and save the value to compare it against each of the somethingX's, but I was wondering if this was a moot point with today's compilers.

I was also unsure of what to google to find the answer to this myself.

Thank you,

AK

like image 255
im so confused Avatar asked Dec 20 '25 05:12

im so confused


1 Answers

It's not moot, especially if the method is mutable.

If getValue is not declared const, the call can't be optimized away, as subsequent calls could return different values.

If it is declared const, it's easier, but also not trivial for the compiler to optimize the call. It would need access to the implementation, to make sure the call doesn't have side effects. There's also the chance that it returns a different value even if marked const (modifies and returns a global).

like image 198
Luchian Grigore Avatar answered Dec 22 '25 18:12

Luchian Grigore