Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a previously defined #define in a new #define in C

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 ) 

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.

like image 947
Oilyraincloud Avatar asked Jan 09 '14 20:01

Oilyraincloud


2 Answers

Macros are NEVER expanded in a #define statement. When you have #define like:

#define ONE_MINUTE ( SAMPLERATE * 60 )

That defines the macro ONE_MINUTE with an expansion (body) of ( SAMPLERATE * 60 ). Whether there is a macro called SAMPLERATE defined elsewhere in your program or not is completely irrelevant. The exisitence (or non-existence) of such a macro has no effect.

Instead, when a macro is USED (and the macro expanded), the result of that expansion is rescanned for other macros to expand. So all that matters is whether SAMPLERATE is defined at the point at which ONE_MINUTE is USED.

like image 107
Chris Dodd Avatar answered Oct 28 '22 13:10

Chris Dodd


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;

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.

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

like image 34
bblincoe Avatar answered Oct 28 '22 12:10

bblincoe