Function Macros

作者: 綿綿_ | 来源:发表于2017-01-11 18:21 被阅读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))

相关文章

网友评论

    本文标题:Function Macros

    本文链接:https://www.haomeiwen.com/subject/tturbttx.html