I know that if you write void function_name(int& a), then the function will not do local copy of your variable passed as argument. Also have met in literature that you should write void function_name(const int & a) in order to say compiler, that I don’t want the variable passed as argument to be copied.
So my question: what is the difference with these two cases (except that const ensures that the variable passed will not be changed by function)?
You should use
constin the signature whenever you do not need to write. Addingconstto the signature has two effects: it tells the compiler that you want it to check and guarantee that you do not change that argument inside your function. The second effect is that enables external code to use your function passing objects that are themselves constant (and temporaries), enabling more uses of the same function.At the same time, the
constkeyword is an important part of the documentation of your function/method: the function signature is explicitly saying what you intend to do with the argument, and whether it is safe to pass an object that is part of another object’s invariants into your function: you are being explicit in that you will not mess with their object.Using
constforces a more strict set of requirements in your code (the function): you cannot modify the object, but at the same time is less restrictive in your callers, making your code more reusable.