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++ 的奇怪行为


基础教程推荐
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 我有静态或动态 boost 库吗? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30