Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of a const value in c if not initialised at declaration? [duplicate]

Tags:

c++

c

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.

like image 951
pradipta Avatar asked Oct 15 '12 08:10

pradipta


People also ask

Why a constant must be initialized when it is declared?

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.

Does const need to be initialized?

An initializer for a constant is required. You must specify its value in the same declaration.

Do const variables need to be initialized?

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.

Can const be initialized?

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.


1 Answers

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.

like image 130
peterchen Avatar answered Oct 23 '22 22:10

peterchen