Saving and Restoring Pragma Settings

There are some occasions when you would like to apply pragma settings to a piece of source code independently from the settings in the rest of the source file. For example, a function might require unique optimization settings that should not be used in the rest of the function's source file.

Remembering which pragmas to save and restore is tedious and error-prone. Fortunately, the compiler has mechanisms that save and restore pragma settings at compile time. All pragma settings and some individual pragma settings may be saved at one point in a compilation unit (a source code file and the files that it includes), changed, then restored later in the same compilation unit. Pragma settings cannot be saved in one source code file then restored in another unless both source code files are included in the same compilation unit.

Pragmas push and pop save and restore, respectively, most pragma settings in a compilation unit. Pragmas push and pop may be nested to unlimited depth. The following listing shows an example.

Listing: Using push and pop to Save and Restore Pragma Settings
/* Settings for this file. */
#pragma opt_unroll_loops on

#pragma optimize_for_size off

void fast_func_A(void)

{

/* ... */

}

/* Settings for slow_func(). */

#pragma push /* Save file settings. */

#pragma optimization_size 0

void slow_func(void)

{

/* ... */

}

#pragma pop /* Restore file settings. */

void fast_func_B(void)

{

/* ... */

}

Pragmas that have a reset option perform the same actions as pragmas push and pop, but apply to a single pragma. A pragma's on and off settings save the pragma's current setting before changing it to the new setting. A pragma's reset option restores the pragma's setting. The on/ off and reset options may be nested to an unlimited depth. The following listing shows an example.

Listing: Using the Reset Option to Save and Restore a Pragma Setting
/* Setting for this file. */
#pragma opt_unroll_loops on

void fast_func_A(void)

{

/* ... */

}

/* Setting for smallslowfunc(). */

#pragma opt_unroll_loops off

void small_func(void)

{

/* ... */

}

/* Restore previous setting. */

#pragma opt_unroll_loops reset

void fast_func_B(void)

{

/* ... */

}