setjmp/longjmp
Long before any C-based language had ever heard of exceptions, there was this tremendously evil pair of functions called setjmp and longjmp. In short, setjmp saves the register state of the machine, and longjmp restores it, causing program flow to jump backwards. This can be used to build an exception-handling system, and indeed Cocoa did just that for a long time.

The trouble is with those pesky registers. Variables are often stored in registers instead of memory. This means that a call to longjmp could actually revert values stored in registers after an assignment had taken place.

Thus one handy use for volatile: declare any variables that this might happen to as volatile, and the compiler will make sure that all assignments go to memory, and thus that their contents will survive the jump.

Advertisements