Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
649 views
in Technique[技术] by (71.8m points)

gcc - Strange behaviour of macros C/C++

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 degrees. Degrees to radians works fine, but radians to degrees does not:

piTest.cpp:

#include <cmath>
#include <iostream>
using namespace std;

#define PI atan(1) * 4
#define radians(deg)  deg * PI / 180
#define degrees(rad)  rad * 180 / PI

int main()
{
  cout << "pi: " << PI << endl;
  cout << "PI, in degrees: " << degrees(PI) << endl;
  cout << "45 degrees, in rad: " << radians(45) << endl;
  cout << "PI * 180 / PI: " << (PI * 180 / PI) << endl;
  cout << "3.14159 * 180 / 3.14159: " << (3.14159 * 180 / 3.14159) << endl;
  cout << "PI * 180 / 3.14159: " << (PI * 180 / 3.14159) << endl;
  cout << "3.14159 * 180 / PI: " << (3.14159 * 180 / PI) << endl;

  return 0;

}

When I compile and run, I get the following output:

pi: 3.14159
PI, in degrees: 2880
45 degrees, in rad: 0.785398
PI * 180 / PI: 2880
3.14159 * 180 / 3.14159: 180
PI * 180 / 3.14159: 180
3.14159 * 180 / PI: 2880

It seems like my constant PI works in the numerator, but not the denominator. I've observed the same behaviour in C. I'm running gcc version 4.6.3

Can anyone explain why I'm getting this behaviour?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Macros are (relatively simple) textual substitutions.

Use parentheses in your definitions (both to enclose the macro itself and the macro arguments):

#define PI (atan(1) * 4)
#define radians(deg)  ((deg) * PI / 180)
#define degrees(rad)  ((rad) * 180 / PI)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...