const qualifier in C language

One thing which I considered to be easy enough not to be taken into consideration but few days ago raised some real issues: const qualifier.

So… what to say about const? Usually the first answer a C programmer gives to this question is const indicates something that cannot change. In reality this is far from being an exhaustive definition of const and it is not even 100% correct.

There are three topics here and just let me take them in order, there are const variables (which is quite straightforward), there are also const functions and const pointers (… and const references). In case of last two, things are complicating a little bit.

Let’s just go back and just slightly correct the assumed definition of const. It is better to say a const variable  is a compile-time fixed variable. By qualifying a variable as const you’re getting a guarantee from the compiler that the variable won’t change through that name.

const int a = 1;
a = 2;

The code above will issue an error (one thing to notice is that const data types always must be initialized) but the one below will not

const int a = 1;
int *b = &a;
*b = 2;

As you may see an object or a data stored somewhere in the memory, can be referenced via an expression.

Here you may find an article exhaustively treating this subject which I strongly recommend you to read. There is a key sentence  highlighted on the first page:

The expression you use to refer an object differs from the object itself.

… and it continues

Sometimes this distinction matters.

Read more of this post

Advertisements