程序猿的读书笔记

Function Macros

2017-01-11  本文已影响0人  綿綿_
Avoid function macros.

In C++,inline functions render functions macros unnecessary; in Java ,there are no macros .In C, they cause more problems than they solve.

A parameter appears more than once in the definition might be evaluated more than once.

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

If it's called like this

?    while(isupper(c =getchar()))
          .....

when an input character is greater than or equal to A ,it will be discarded and another char read to be tested against Z.
Rewriting the test use two expressions rather than one makes it clearer and gives an opportunity to catch end-of-file explicitly.

 while(( c=getchar()) != EOF && isupper(c))
          .....
Parenthesize the macro body and arguments

Macros work by text substitution.

1 / square(x)

works fine as a function
but if it's a macro like

?   #define square(x) (x)*(x)

the expression will be expanded to the erroneous.
it should be written as

#define square(x) ( (x) * (x))
上一篇 下一篇

猜你喜欢

热点阅读