在C中的新#define中使用先前定义的#define [英] Using a previously defined #define in a new #define in C

查看:134
本文介绍了在C中的新#define中使用先前定义的#define的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在进行诸如以下操作时是否存在任何潜在的问题/危险

Are there any potential issues/dangers in doing something such as

#define SAMPLERATE 32 // Sample rate in hertz
#define ONE_MINUTE ( SAMPLERATE * 60 )
#define FIVE_MINUTES ( ONE_MINUTE * 5 ) 

我的编译器没有发出任何错误或警告。很好,因为我可以更改一个 #define 值(SAMPLERATE),而其他所有值都将设置为所需的值,而无需进行其他更改。我只是不完全确定这是最佳做法还是安全。

My compiler doesn't issue any errors or warnings. It's very nice because I can change one #define value (SAMPLERATE) and all the others get set to what they need to be with no other changes. I'm just not entirely sure if this is best practice or safe.

推荐答案

A #define 由预处理器处理。该预处理器在编译之前运行,并且可以执行简单的数学运算以及复制/粘贴代码。例如,您可以对示例执行以下操作:

A #define is handled by the pre-processor. The pre-processor is run prior to compilation and can perform simple mathematical operations and copy/paste of code. For instance, you could do the following with your example:

int myVar = SAMPLERATE;

预处理器只需在编译前粘贴 32 其中 SAMPLERATE

The pre-processor would simply paste 32 where SAMPLERATE is before being compiled.

在您已经为整数值创建名称的意义上,此机制非常强大。这为您和未来的开发人员增加了意义。

This mechanism is powerful in the sense that you have now created a name for an integer value. This adds meaning for both you and future developers. It also allows you to make changes in one place instead of many.

只需确保 #define SAMPLERATE 32 在可能使用 SAMPLERATE 的任何其他 #define 语句之前。

Just be sure to #define SAMPLERATE 32 prior to any other #define statements that may use SAMPLERATE.

这篇关于在C中的新#define中使用先前定义的#define的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆