hari
hari

Reputation: 9743

Issue with function macro

The Practice of Programming book says:

One of the most serious problems with function macros is that a parameter that appears more than once in the definition might be evaluated more than once; if the argument in the call includes an expression with side effects, the result is a subtle bug. This code attempts to implement one of the character tests from :

#define isupper(c) ((c) >= 'A' && (c) <= 'Z')

Note that the parameter c occurs twice in the body of the macro. If i supper is called in a context like this,

while (isupper(c = getchar()))

then each time an input character is greater than or equal to A, it will be discarded and another character read to be tested against Z.

I do not understand how a char greater >= A can be discarded.

Upvotes: 4

Views: 206

Answers (1)

Fred Foo
Fred Foo

Reputation: 363817

Since macro definitions are expanded textually into the program before the actual compilation,

isupper(c = getchar())

would expand to

((c = getchar()) >= 'A' && (c = getchar()) <= 'Z')

which by the short-circuiting rule for && calls getchar twice iff it returns >= 'A' the first time and assign c the value returned by the second call.

Upvotes: 6

Related Questions