Docsity

Macro Programming in C: Understanding Define, Precedence, and Parentheses, Slides of Operating Systems

Partial preview of the text

Download Macro Programming in C: Understanding Define, Precedence, and Parentheses and more Slides Operating Systems in PDF only on Docsity!

#define

Sep. 13, 2013

Dave Eckhardt Dave Eckhardt Todd Mowry Todd Mowry L08a_define

“Don't make me stop the car...”

Outline

What's wrong with this picture? What's wrong with this picture?

Example 1 – Change Requirement

From: Dave Eckhardt Subject: keyboard buffer size Keyboard buffers must handle somebody placing a cat on the keyboard (the 101-key keyboard).

Example 1 – Cat On Keyboard

Photo credit: Ivan Jager, 2006-10-

Option 2

int scanbuf[64]; int getchar(void) { ... if (++bufindex == 256) bufindex = 0; ... }

Option 3 – Try This At Home!!!

#define KSB_SIZE 256 int scanbuf[KSB_SIZE]; int getchar(void) { ... if (++bufindex == KSB_SIZE) bufindex = 0; ... }

Example 2 – Truly Pernicious

How to fix How to fix halfhalf of the problemof the problem % grep 64 *.c Wrong Wrong twotwo waysways  (^) Won't find 63  (^) Will find random unrelated 64's

Example 3

#define CENTER_X 40 #define CENTER_Y 12 ... set_cursor_pos(CENTER_Y, CENTER_X); ...

Example 4

p->regsave[-18] |= 0x402; ... Don't make me stop the car...... Don't make me stop the car......

Multiplicity

#define INC_TWICE(x) ++x; ++x // Note: only one ';'

Multiplicity

#define INC_TWICE(x) ++x; ++x INC_TWICE(ac); ⇒ ++ac; ++ac;

Multiplicity

#define INC_TWICE(x) ++x; ++x INC_TWICE(ac); ⇒ ++ac; ++ac; if (ac) INC_TWICE(ac);

Multiplicity

#define INC_TWICE(x) ++x; ++x What to do? What to do?  (^) See “multi-line macro”

Precedence and Parentheses

#define TWICE(x) 2x TWICE(3) / 2*3 ⇒ 6 */