Pooria
Pooria

Reputation: 2055

May a compiler optimize a reference to constant parameter to constant value?

Consider following function:

void func(const char & input){
 //do something
}

Apparently it makes sense for the parameter to be constant value not reference to constant regarding size of the char type, Now may a compiler optimize that to constant value so that it'll be the same as following ?

void func(const char input){
 //do something
}

Upvotes: 2

Views: 254

Answers (3)

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 507423

Like someone stated, but was sadly downvoted (not sure why he did delete his answer), the compiler can do any and everything as long as the observable behavior is the same as if it did not do anything different.

It's self-expanatory that if your function writes into the reference, and a global variable was passed as argument to the function and the global was later printed after the function returns, or anything else fancy is done, then if the compiler would change the parameter passing convention, it's more difficult for the compiler to prove you still get the same observable behavior. If the compiler can't prove it, it can't do the desired optimization.

So whatever further question comes up, just think "it can do anything as long as I won't notice it".

Upvotes: 2

user180326
user180326

Reputation:

As noted, not in general. But what the compiler can do is inline the entire function call. And if the parameter supplied is a compile time constant, it can do lots of interesting optimizations.

Upvotes: 1

Henrik
Henrik

Reputation: 23324

No. This is not equivalent. In the first case, input can still change, e.g. if it's a reference to a variable that's modified by another thread.

Upvotes: 5

Related Questions