-
Const vs int
Hi guys! Do not really understand the difference between the two following way of declarations:
int x=2;
const int x=2;
I can figure out that the second one should be a constant and the first one a variable, but what is the real difference between them in the manner of functionality?
-
The second statement is read-only data, it would act like x is an alias for the integer value 2. In the second statement you would not be able to change what x is...
...unless you use a const_cast but that's for another thread.
-
It would be illegal to use a const_cast on that and subsequently attempt to modify it. If you did try to, it quite likely may not allow you to change the value, as it may reside in a read-only memory location.
You use the const case when you know x wont change, or specifically want to ensure that x is not changed, during its lifetime.
-
Well, you got the whole cannot change part--trying to change it is not allowed since it's const. You can argue that's part of its functionality, but I suppose you're looking for more than this.
This part is tricky. In C++ there's something called a constant expression. What that means is that it's an expression which the compiler can deduce at compile time. For example, when creating an array, you must specify its size. The compiler must be able to determine its size at compile time. Therefore, the size must be a constant expression.
Normal variables aren't constant expressions because they can change. However, along with certain limitations, const variables can be constant expressions. If they are declared locally or globally (and not as function parameters) and initialized with a constant expression (say, an integer), then they are considered constant expressions and are basically substituted for its value at compile time.
That's basically all the difference between the two unless I'm forgetting something.
-
Thanks guys, all of you!
I think for now its enough for me to know that the difference is that const make the integer nonchangeable.
By the way guys! any tips how or where to find good and easy exercises to solve? I need lots of practicing :-)