Do compilers optimize out parameters that aren't used?

  • A+
Category:Languages

Suppose I have a very simple inline function:

void Trace(int i) { #ifdef _DEBUG     std::cout << i << std::endl; #endif } 

Now I call this function with the parameter generated by another function that takes a long time:

Trace(SlowFunc()); 

Will a reasonable compiler optimize out the call to SlowFunc() in release mode? Specifically will MSVC do it?

 


The optimization would only be allowed if SlowFunc() is proven to have no side effects - but in practice, long-running functions are usually ridden with side-effects (unless it is some sort of heavy computational math, but then the optimizer might give up on it). If SlowFunc() is proven to have no side effects, this call can be optimized out.

But I would not rely on it. Instead, use a logging solution which only calculates the argument when DEBUG is enabled. There are a couple of options, let me know if you'd like some pointers.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: