### Example of volatile Variables in a Signal Handler

Because of the way the IBM C and C++ Compilers optimizes code, the following example may not work as intended if it is compiled with the optimization options.

    #include <io.h>
    #include <signal.h>
    #include <stdio.h>
    #include <string.h>

    void sig_handler(int);
    static int stepnum;

    int main()
    {
       stepnum = 0;
       signal(SIGSEGV, sig_handler);
       /* code omitted - does not use stepnum */
       stepnum = 1;
       /* code omitted - does not use stepnum */
       stepnum = 2
       return 0;
    }

    void sig_handler(int x)
    {
       char FileData[50];
       sprintf(FileData, "Error at Step %d\n\r", stepnum);
       _write (2, FileData, strlen(fileData));
    }

An optimized program may not immediately store the value 1 when 1 is assigned to the variable stepnum. It may never store the value 1 and only store the value 2. If a signal occurs between the assignments to stepnum,, the value passed to sig_handler may not be correct.

Declaring stepnum as volatile indicates to the compiler that references to this variable have side effects. Changes to the value of stepnum are then stored immediately.

Example of a C Signal Handler

Signals and Exceptions
Signal and Exception Handling

Program Signal Handling
Write or Register a Signal Handler

Signals and Default Handlers