Strange behaviour of macros C/C++

前端 未结 5 621
再見小時候
再見小時候 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条回答
  •  猫巷女王i
    2020-12-04 03:19

    First, cmath defines M_PI, use that.

    Second, cpp macros do textual substitution. Which mean that this:

    #define PI atan(1) * 4
    a = 1 / PI;
    

    will be turned into this:

    a = 1 / atan(1) * 4;
    

    before the c/c++ compiler gets a chance to see your code, and it will treat it equivalent to this:

    a = (1 / atan(1)) * 4;
    

    which is not what you want.

    Your define should look like this:

    #define PI (atan(1) * 4)
    

    and everything should be fine.

    This is not really strange behaviour, but well documented behaviour of the c-preprocessor.

    You should search the web for other pitfalls with macros. (hint: parameter passing)

提交回复
热议问题