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

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
/* the fix */
#define ceil_div_fix(x,y) ((x) + (y) - 1)/(y)

int main () {
   unsigned char b = 0x3, c = 0x1;
   printf("result> %d, %d, %d\n", 
              ceil_div(b & c, sizeof (int)), 
              ((b & c) + sizeof(int) -1)/sizeof(int),
              ceil_div_fix(b & c, sizeof(int)));
 -  A simple fix is to force evaluation of all arguments by putting parens around their occurrences in the macro. Alternatively, the parens can be placed around the parameters.