C/C++ Macros





Macros in Macros

The sequence

#define PI 3.14159 #define AREA RADIUS * RADIUS * PI x = AREA ; #define RADIUS 2.0 y = AREA ;

expands to

x = RADIUS * RADIUS * 3.14159 ; y = 2.0 * 2.0 * 3.14159 ;

After expanding a macro, the prepocessor checks if the resulting text has more macros to expand.




Function-like Macros





Macros vs Functions





Multiple Lines in a Macro





Eating the Trailing Semicolon





Macro Pitfalls





Further Reading on Macros

Other issues:

More on C/C++ macros can be found on the GNU compiler web site.




A Macro for Selection Sort

#define SWAP(TYPE, X, Y) \ do { TYPE temp=X; X=Y; Y=temp;} while(0) #define SelectionSort(T, A, n) \ for (int i=0 ; i < n ; i++) { \ for (int j=i+1 ; j < n ; j++) { \ if (A[i] > A[j] ) SWAP(T, A[i], A[j]) ; \ } \ }



A Macro for Quicksort?





Problems with Quicksort "Macro"