5. Macros
• We can #define constants
#define HALF_PI 1.5708
#define BAD_PI HALF_PI+HALF_PI
• Solution?
((((((((((The parentheses!))))))))))
#define PI ((HALF_PI)+(HALF_PI))
6. Parameterized Macros
• Macros with param :
#define BAAAD_DOUBLE(x) (x*2)
#define BAD_DOUBLE(x) ((x)+(x))
#define OKAY_DOUBLE(x) ((x)*2)
• WHAT TO TAKE HOME:
– Don’t use 2+ parameters.
– No assignments within macro
7. Parameterized Macros cont’d
• Want to wrap malloc() calls.
– Can we?
• YES!
#define NEW_T(t,sz)
((t*) malloc((sz)*sizeof(t))
8. Appropriate use of Macros
• Do
– Use parentheses
– Handle header file inclusion
– Capitalize macro names
• Don’t
– Use more than 2 parameters.
– Replace function calls with macros for
‘performance’
– Make the code harder to read
#define LOOP(s) while(1) {s};
15. Example %c, %s conversion
• %c has only precision 1
• Precision in %s means string length
starting from the beginning
• Padding and justification are same