Strange behaviour of macros C/C++(宏 C/C++ 的奇怪行为)
问题描述
我正在使用一些宏,并观察到一些奇怪的行为.
I'm using some macros, and observing some strange behaviour.
我将 PI 定义为一个常数,然后在宏中使用它来将度数转换为弧度,将弧度转换为度数.度数到弧度可以正常工作,但弧度到度数不能:
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:
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
我的常数 PI 似乎适用于分子,但不适用于分母.我在 C 中观察到相同的行为.我正在运行 gcc 版本 4.6.3
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?
推荐答案
宏是(相对简单的)文本替换.
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)
这篇关于宏 C/C++ 的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:宏 C/C++ 的奇怪行为
基础教程推荐
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- CString 到 char* 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
