Possible Duplicate:
const in C vs const in C++
I have following code
In C
int main()
{
const int k;//allowed but garbage and later we can't modify
printf("%d",k);
}
o/p=Garbage
In C++
int main()
{
const int k; //not allowed from here itself
printf("%d",k);
}
o/p-compile time error
I having doubt what is the use of the const
in C if it it is allowed
to declare it with out initialization
but after it declaration
we can't initialize
it.
But is c++
it is good that we can't declare a const
value without initialization
.
Is there any use of the variable k
in C
or it is useless,if we only declare it as later modification is not possible.
When a variable is declared as const it means that , variable is read-only ,and cant be changed . so in order to make a variable read only it should be initialized at the time it is declared.
An initializer for a constant is required. You must specify its value in the same declaration.
A constant variable must be initialized at its declaration. To declare a constant variable in C++, the keyword const is written before the variable's data type.
To initialize the const value using constructor, we have to use the initialize list. This initializer list is used to initialize the data member of a class. The list of members, that will be initialized, will be present after the constructor after colon. members will be separated using comma.
It has no use by itself.
However, there are compiler specific extensions where this becomes useful again.
C Compilers for embedded platforms
, for example, often have extensions that allow to give a variable a fixed address, or as an alias for an memory mapped I/O port.
The const
would indicate / enforce that you only read
from that address, for example a memory mapped input port.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With