Using volatile to Prevent Optimization of try/except

Last reviewed: November 2, 1995
Article ID: Q91149
The information in this article applies to:
  • Microsoft Win32 Application Programming Interface (API) included with:

        - Microsoft Windows NT versions 3.1, 3.5, and 3.51
        - Microsoft Windows 95 version 4.0
    

SUMMARY

The following is an example of a valid optimization that may take programmers by surprise.

  1. A variable (temp) used only within the try-except body is declared outside it, and therefore is global with respect to the try.

  2. Assignment to the variable (temp) is in the program only for a possible side effect of doing a read memory access through the pointer.

MORE INFORMATION

For example:

   VOID
   puRoutine( PULONG pu )
   {
      ...
      ULONG temp;       // Just for probing
      ...
      try {
         temp = *pu;    // See if pu is a valid argument
      }

      except {
         // Handle exception
      }
   }

The compiler optimizes and eliminates the entire try-except statement because temp is not used later.

If the value of temp were used globally, the compiler should treat the assignment to temp as volatile and do the assignment immediately even if it is overwritten later in the body of the try. The reasoning is that, at almost any point in the try body, control may jump to the except (or an exception filter). Presumably the programmer accessing the variable outside the try wants to get the current (most recently assigned) value.

The way to prevent the compiler from performing the optimization is:

   temp = (volatile ULONG) *pu;

If a temporary variable is not needed, given the example, the read access should still be specified as volatile, for example:

   *(volatile PULONG) pu;


Additional reference words: 3.10 3.50 4.00 95
KBCategory: kbprg
KBSubcategory: BseExcept


THE INFORMATION PROVIDED IN THE MICROSOFT KNOWLEDGE BASE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. MICROSOFT DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING THE WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL MICROSOFT CORPORATION OR ITS SUPPLIERS BE LIABLE FOR ANY DAMAGES WHATSOEVER INCLUDING DIRECT, INDIRECT, INCIDENTAL, CONSEQUENTIAL, LOSS OF BUSINESS PROFITS OR SPECIAL DAMAGES, EVEN IF MICROSOFT CORPORATION OR ITS SUPPLIERS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME STATES DO NOT ALLOW THE EXCLUSION OR LIMITATION OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES SO THE FOREGOING LIMITATION MAY NOT APPLY.

Last reviewed: November 2, 1995
© 1998 Microsoft Corporation. All rights reserved. Terms of Use.