Posts Tagged ‘keyword’

Volatile: C Keyword Myths Dispelled

Tuesday, February 24th, 2009

Subscribe To Our Feed | Follow Us On Twitter | Get Updates on Email

Last time we explained the real meaning of const keyword, this time it’s going to be Volatile, the other sibling of this most misunderstood duo in C history. Let’s separate out the myths and the facts first and then we will discuss the how’s and why’s of it.

FACTS:

  • A volatile qualifier is important to be used for auto-storage variables within setjmp and longjmp.
  • A volatile qualifier must be used when reading the contents of a memory location whose value can change unknown to the current program.
  • A volatile qualifier must be used for shared data modified in signal handlers or interrupt service routines.

MYTHS:

  • All shared data in multi-threaded programs must be declared volatile.

Now, we’ll see how we made the above classfication.

(more…)

© Safer Code | Volatile: C Keyword Myths Dispelled

Liked this post? Get FREE Updates
Subscribe to RSS feed

Or
Enter Your E-mail ID below

"const" Keyword Explained

Wednesday, February 4th, 2009

Subscribe 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:

(more…)

© Safer Code | "const" Keyword Explained

Liked this post? Get FREE Updates
Subscribe to RSS feed

Or
Enter Your E-mail ID below