The const keyword means that you can't change the value of x. So trying to do x=4; is illegal.
The & symbol means that x is a reference, rather than being passed in by value. This means that if the function changes the value of x, then the value of the variable in the calling code will also be changed. However, you're not passing in a variable - you're passing in an integer literal, so even if you weren't declaring x to be const, you wouldn't be able to do it anyway. After all, how could you change the value of 4?
What is it that you want your function to actually do?
But int * const cpc would declare a constant point to an int.Why would int& const x generate an error?
Constness in pointer types is slightly more fiddly, because you can specify both that the pointer itself remains constant (i.e. the pointer will always point to the same memory address), and/or that the object pointed to will remain constant when accessed via the pointer.
It depends on where you put the word const. If you put it before the type of object pointed to, e.g. constint* i;
then it means the value of the integer is constant. It is a pointer to a constant integer.
If you put it after the *, e.g.
int* const i;
then it means the pointer itself is constant. It is a constant pointer to an integer.
So, you can have the following:
1 2 3 4 5 6
int myValue = 0;
intconst* i = &myValue; // This specifies that the pointer itself is constant
*i = 173; // This is legal - the value of the integer being pointed to can be changed
int myOtherValue = 1;
i = &myOtherValue; // ERROR - you cannot change the address that the pointer points to.
Or you can have:
1 2 3 4 5 6
int myValue = 0;
constint* i = &myValue; // This specifies that the object pointed to is constant
*i = 173; // ERROR - this is illegal - you cannot change the value of the integer being pointed to
int myOtherValue = 1;
i = &myOtherValue; // This is OK - you can change the address of the pointer to point to another integer.
You can even have:
1 2 3 4 5 6
int myValue = 0;
constint* const i = &myValue; // This specifies that the object pointed to is constant AND that the pointer itself is constant.
*i = 173; // ERROR - this is illegal - you cannot change the value of the integer being pointed to
int myOtherValue = 1;
i = &myOtherValue; // ERROR - you cannot change the address that the pointer points to.
In your case, you are declaring that the pointer is constant, but not the integer itself. The compiler doesn't complain, because you are not changing the pointer, just the value of the integer.
A reference (&) can be set only once: at initialization. more const isn't possible hence adding const to the reference is considered illegal. It's a matter of definition