#define vs. const vs enum

时间:2022-05-03 03:20:34

In one word, using const is better than define. enum is the best.

There are lots of discussions. I put a great paper below.

https://betterembsw.blogspot.com/2017/05/define-vs-const.html

The compiler might generate storage for a constant object, even though the program doesn't really need that storage. It might even generate additional code to initialize the constant at run time.

Another way is using enum, which will not generate the additional code.

example.

uint8_t GetAddressValues(void)
{
/* The counter of ADC channel
* There are four channels for reading 1, 2, 4, 8
* who corresponding to bit 0, bit 1, bit 2, bit 3
*/
//#define ADC_CHANNELS_COUNT (4)
//const uint8_t ADC_CHANNELS_COUNT = 4; /* select the ADC with VR+ = VCC and VR- = VSS
* 16 × ADC10CLKs, ADC10 on, Interrupt disabled
* HIGH_LEVEL_VALUE is the value of high level gate
* it is high level when it is greater than HIGH_LEVEL_VALUE,
* otherwise, it is low.
*
* HIGH_LEVEL_VALUE is based on the Vin of high level (0.424V)
* HIGH_LEVEL_VALUE = 1023 * 0.424/3.3 = 131.44
*/
//#define HIGH_LEVEL_VALUE (132)
//const uint8_t HIGH_LEVEL_VALUE = 132; enum
{
ADC_CHANNELS_COUNT = , //ADC channels counter
HIGH_LEVEL_VALUE = , //high level threshold
};
}