I am learning C++. In my course, it is explained that it is best to place const
immediately after the thing you want to make unchangeable, because this is how const
works.
Many people, including for instance Bjarne Stroustrup himself, like to write const
in front. But this sometimes leads to problems:
const int *foo; //modifiable pointer to a constant int.
int const *bar; //constant pointer to a modifiable int? No! It's a modifiable pointer to a constant int. (So the same type as foo)
An example that shows this in action:
int fun(int const *mypointer)
{
*mypointer = 5; //Won't compile, because constant int.
mypointer = 0; // Is okay, because modifiable pointer.
}
What makes this even more confusing, is that compilers such as g++ like to rewrite int const bar
to const int bar
in their error messages.
Now, this behaviour is confusing me greatly. Why does const
work in this way? It would seem a lot easier to understand if it would 'just' work on the thing put after it.