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

Lambda calculus, Type theory, Formal semantics, Program analysis

    Prev     Next     All lectures        Code

Macros in the C language

#include <stdio.h>

/* operator in x may cause error */
#define ceil_div(x,y) (x + y - 1) / y

int main () {
   unsigned char b = 0x3, c = 0x1;
   printf("result> %d, %d\n", 
              ceil_div(b & c, sizeof (int)), 
              ((b & c) + sizeof(int) -1)/sizeof(int));

/* ceil_div -> (b & c + sizeof(int) - 1)/sizeof(int) */
 -  But things can go wrong. In this example the textual substitution is shown commented to the left. Operator precedence causes the addition to happen before the & leading to the wrong result.