Problem with function macro

The book "Programming Practice" says:

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

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

Note that the c parameter occurs twice in the body of the macro. If I have dinner in a context like this,

 while (isupper(c = getchar())) 

then each time the input character is greater than or equal to A, it will be discarded, and the other character will be read for testing against Z.

I do not understand how you can drop the char anymore> = A.

+4
source share
1 answer

Since macros are deployed to a program before actual compilation,

 isupper(c = getchar()) 

will expand to

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

which, according to the short circuit rule for && calls getchar twice if it returns >= 'A' first time and assigns c value returned by the second call.

+6
source

Source: https://habr.com/ru/post/1379048/


All Articles