Strange behaviour of macros C/C++

前端 未结 5 620
再見小時候
再見小時候 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:24

    Macros just do text substitution without regard for context, so what you wind up with is:

    cout << "PI, in degrees: " << atan(1) * 4 * 180 / atan(1) * 4 << endl;
    

    Note the distinct lack of parens around the second atan(1) * 4, causing it to divide only by atan(1) and then multiply by 4.

    Instead, use inline functions and globals:

    const double PI = atan(1) * 4;
    double radians(double deg) { return deg * PI / 180; }
    double degrees(double rad) { return rad * 180 / PI; }
    

提交回复
热议问题