0

I would like to better understand how changing function signature from say:

void foo(double x);

to:

void foo(const double x);

if we don't modify the x inside, can lead to some optimization tricks on behalf of the compiler. Can someone give me a specific, concrete example?

gruszczy
  • 40,948
  • 31
  • 128
  • 181
  • Related: [Const correctness for value parameters](http://stackoverflow.com/questions/1724051/const-correctness-for-value-parameters) – Shafik Yaghmour Aug 01 '13 at 17:04
  • Making function parameters and local variables const usually does not result in extra optimizations (except maybe in debug mode). – Neil Kirk Aug 01 '13 at 17:18

3 Answers3

4

The change you've made has no effect. x is passed by value in both cases, so declaring it const doesn't affect anything at the call site. The only difference is that inside your implementation of foo you won't be allowed to modify x in the second case. There's no reason to give yourself such a restriction though - if you don't modify x, the compiler will probably make suitable optimizations even in the absence of the const.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469
3

Modern compilers can usually figure this out anyway, assuming the code in the foo function is available to the compiler - if it isn't there's little the compiler can do either way.

It is much more important for the promise (or contract, if you prefer) of not modifying pointer/reference/array variables passed to a function - and more for the programmer calling the function, knowing that there is no problem with the value being modified. But for simple value variables, they are copies anyway, so there's no difference at all.

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
2

This is actually usually used as a correctness aid rather than for any compiler optimization. If you has a pass-by-value, marking it const like this will prevent you from accidentally modifying the parameter when you intended something else.

Even so it's still not an entirely common form.

Theoretically it could enable the compiler to load from memory into a register once and avoid rereading the value, but the compiler can often figure this out on its own without help because unless you go out of your way to alias the parameter the compiler can see where it's being updated within the function's scope.

Mark B
  • 95,107
  • 10
  • 109
  • 188