The const keyword (part 1)

Posted by Strainu on May 24, 2007
C, C++

This article will not actually present any tricks, it will be an introduction in the const keyword. In part 2, we will present the const and volatile pointers, which behave a little weird.

First of all, let’s see what the const modifier means in the C standard. Basically, a const variable is one who’s value can’t be changed. Actually, things are not so simple – as we’ll see later, you can change a constant variable. The standard states that “If an attempt is made to modify an object defined with a const-qualified type through use of an lvalue with non-const-qualified type, the behavior is undefined.” On some architectures, constant variables are put in a special section (sometimes called .rodata – from Read Only DATA) of the program by the compiler.

If you want to define a constant in C/C++, you can write:

const int v1 = 0; //the usual way
int const v2 = 1; //also legal

Both declarations mean the same thing: define a new integer with a fixed value. So, if you want to change the value of v1, how would you do it? By using pointers:

const int v1 = 0; //define a constant
int* v2 = &v1; //define a pointer to v1
*v2 = 5; //change the value

Of course, you shouldn’t do that, as the are no guarantees that the result will be what you expect it to be, but with most compilers, v1 will be 5 after running the code presented above.

Share and Enjoy:
  • Facebook
  • Twitter
  • Identi.ca
  • LinkedIn
  • Reddit
  • Add to favorites

Tags: ,

1 Comment to The const keyword (part 1)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.