Well,correct me if I'm wrong,but if I create a constant like:
const int x = 10;
Wherever I use that x,shouldn't the compiler just insert 10? If it's true,it inserts 10 wherever needed,but after that,why keep it?
The compiler can do that, but it doesn't have to; furthermore in certain situations, const variables MUST be treated as literals, in certain other situations, they can't be.
For example, with code like this:
const int x=10;
...
for (i=0; i<x; ++i){...}
the compiler can treat the variable x in the for statement as if it were a literal 10, although it is not required to. But, in this code:
const int x=10;
...
int array[x];
in C++, the x in the array declaration MUST be treated as a literal 10. In C, it may be, but isn't required to (at least under the C99 and C11 standards; under older standards, it simply won't compile).
On the other hand, if you do this:
const int x=10;
...
const int *px=&x;
the compiler is required to allocate storage for x, regardless of how it deals with x elsewhere in the code.
And while you may find yourself asking why you would take the address of a constant, here's a more familar-looking snippet of code that does just that:
std::string hw="Hello World!";