R
Rajesh
Dear All,
Where to use volatile variable?
Thanks
Rajesh
Where to use volatile variable?
Thanks
Rajesh
Rajesh said:Dear All,
Where to use volatile variable?
Rajesh said:Dear All,
Where to use volatile variable?
Thanks
Rajesh
In said:Where to use volatile variable?
In <[email protected]>
Anywhere the value of an object may change behind compiler's back.
My favourite example:
#include <stdio.h>
#include <signal.h>
volatile sig_atomic_t gotsig = 0;
void handler(int signo)
{
gotsig = signo;
}
int main()
{
signal(SIGINT, handler);
puts("Press the interrupt key to exit.");
while (gotsig == 0) ;
printf ("The program received signal %d.\n", (int)gotsig);
return 0;
}
In said:I don't see a guarantee in the standard that an object of type
sig_atomic_t can hold the value SIGINT (though I don't know of an
implementation where it can't).
If it cannot, the result will be implementation-defined. The program's
overall behaviour is not affected. In C89, at least.
In said:In C89, if the value of SIGINT doesn't fit in a sig_atomic_t, the
program's output will be incorrect; it might print, for example,
The program received signal 42.
even though the actual value of SIGINT might be, for example, 298. It
doesn't affect the program's flow of control (if that's what you mean
by "overall behavior"), but it certainly affects its behavior.
In C99 the conversion of the value of SIGINT to sig_atomic_t could
even raise an implementation-defined signal under certain
circumstances.
Who cares? The program still behaves as expected, and the probability
of this happening is zilch. You'd have a point if it were a real
life program (and not a demo) and if the wrong value would cause
unexpected/unintended behaviour.
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.