You can never change the data-type of any variable. If you have const int
it is the same as int const
always. Though, for function declarations, there are special cases.
Actually,
int add(const int a, const int b);
and
int add(int a, int b);
Or any combination of const
in it all declare the same function. To outside, they are all the same and have actually also all the same type. It only matters for definition of functions. If you don't put const
int add(int a, int b) { a++; /* possible, increment the parameter */ }
you can change the parameters (which in this example are copies of the arguments passed). But if you put const, parameters will be const within the function definition
int add(int const a, int const b) {
a++; // bug, a is a constant integer!
}
Why does it not matter whether you write const or not for function declarations? Because the argument will be copied, and so it will not have any impact on the caller and the callers arguments anyway! For that reason, the following style is recommended. In a header, declare the functions without const
int add(int a, int b);
Then, in the definition, if you want a parameter to be const, put the const in.
#include "add.hpp"
// remember, const int and int const is the same. we could have written
// int add(const int a, const int b); too
int add(int const a, int const b) { return a + b; }
Same counts for member functions
struct foo {
void f(int);
};
void foo::f(int const a) { ... }
Note that we only talked about the const that affects the constness of the parameter directly. There are other const that affect constness when using references or pointers. Those consts are not to be ignored and are actually important.