20-CS-4003-001 Organization of Programming Languages Fall 2017
Macros

Lambda calculus, Type theory, Formal semantics, Program analysis

    Prev     Next     All lectures        Code

Macros in the C language

#include <stdio.h>

/* accidental capture of identifiers
   compile with:
     gcc slide01.cc -o slide01
     gcc -Wshadow slide01.cc -o slide01
*/

#define INCI(i) {int a=0; ++i;}

int main() {
   int a = 0, b = 0;
   INCI(a);
   INCI(b);
   printf("a = %d, b = %d\n", a, b);
   return 0;
}

/* preprocessor makes this:
int main(void) {
   int a = 0, b = 0;
   {int a=0; ++a;};
   {int a=0; ++b;};
   printf("a = %d, b = %d\n", a, b);
   return 0;
}
*/
 -  Even worse, a macro might accidentally capture an identifier that is used outside the macro and affect its value as shown in the example to the left. The macro expansion is shown commented at the bottom. Such a macro facility is called unhygienic.