Bad parentheses in macro definition

前端 未结 1 1649
感情败类
感情败类 2021-01-22 02:31

I was reading this tutorial of stanford where they say :

Common coding mistakes:

Bad parentheses in macro definition

#define mi         


        
相关标签:
1条回答
  • 2021-01-22 03:02

    The first version fails if you combine it with other operators:

    min(a , b) + c 
    

    and translates to:

    a<b?a:b+c 
    

    which is identical to:

    a<b?a:(b+c) 
    

    which is an unexpected outcome given the starting parenthesis.

    The second version isn't much better. It evaluates one of the parameters twice which can cause unexpected behavior if a function or i++ is passed to the macro.

    An inline function should be used instead of those macros.

    0 讨论(0)
提交回复
热议问题