Strange behaviour of macros C/C++

前端 未结 5 598
再見小時候
再見小時候 2020-12-04 03:02

I\'m using some macros, and observing some strange behaviour.

I\'ve defined PI as a constant, and then used it in macros to convert degrees to radians and radians to

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-04 03:23

    Also good practice: Add brackets around all your parameters:

    #define radians(deg)  ((deg) * PI / 180)
    

    because the expression you pass as parameter might include operators, too.

    Or even better: Use (inline-) functions instead of macros, to avoid surprises with sideeffects when a parameter is evaluated multiple times like here:

    #define sqr(x)  ((x) * (x))
    

    The only disadvantage you get with inline functions: You can define them for one type, only (unless you use C++ templates)

提交回复
热议问题