"const" Keyword Explained
Wednesday, February 4th, 2009Subscribe To Our Feed | Follow Us On Twitter | Get Updates on Email
There are a few very basic things in C that are widely misunderstood by programmers of all caders. This is not because these things are very complex, but because books and teachers do not give them their due importance while teaching beginners and the misconceptions stick even years later. A few of these are like the keywords “volatile” (covered in next post) and “const”.
Look at the following piece of code:
#include <stdio .h> int main() { const int a = 1; a = 2; printf("%d\n", a); return 0; }</stdio>
You’d be quick to point out (correctly) that the above code wouldn’t compile. It would fail with an error on the lines of “assignment of read-only variable a” because a is now a “constant” because of the const type qualifier attached to it. And now comes the issue. Many start assuming (or might even be explicitly taught) that the value of a cannot be changed now. Did you think so too? Well, you thought wrong. Look at the following code:
© Safer Code | "const" Keyword Explained
|
Liked this post? Get FREE Updates Subscribe to RSS feed |