An object that has volatile-qualified type may be modified in ways unknown to the implementation or have other unknown side effects. Asynchronous signal handling falls under these conditions. Without this type qualifier, unintended optimizations may occur.
The volatile keyword eliminates this confusion by imposing restrictions on access and cacheingcaching. According to the C99 Rationale:
...
| Code Block | ||
|---|---|---|
| ||
#include <signal.h>
size_t i;
void handler() {
i = 0;
}
int main(void) {
signal(SIGINT, handler);
i = 1;
while(i) {
/* do something */
}
}
|
Compliant Solution
i will now be is accessed again for every iteration of the while loop.
| Code Block | ||
|---|---|---|
| ||
#include <signal.h>
volatile size_t i;
void handler() {
i = 0;
}
int main(void) {
signal(SIGINT, handler);
i = 1;
while(i) {
/* do something */
}
}
|
...