I am currently using static const in my code instead of using the "magic numbers" mentioned in the "static const" vs "# define" vs "enumeration" .
void checkInvalidResponse (uint8_t response) { static const uint8_t INVALID_RESP = 0xFF; if (response == INVALID_RESP) { } }
However, I believe that using static const will consume memory in compiled code for INVALID_RESP. The operator will also translate to machine code, which makes a LOAD from memory, followed by a comparison, instead of comparing with the value provided as part of the instruction. It's right? If so, then this solution will not be optimal in terms of speed and memory?
I am currently modifying the code to use #defines
void checkInvalidResponse (uint8_t response) { #define INVALID_RESP 0xFF if (response == INVALID_RESP) { } }
However, since #define has no scope, will the behavior of the cut-and-paste attribute in #define be consistent across multiple compilers? For example, if INVALID_RESP is redefined later, will any code in the lines after the redefinition use the new value?
Another approach I reviewed is using enums.
void checkInvalidResponse (uint8_t response) { typedef enum { INVALID_RESP = 0xFF } resp_t; if ((resp_t)response == INVALID_RESP) { } }
However, casting to an enumeration will allocate more memory than necessary (the processor will compare 32 bits (?) Instead of 8-bit comparison).
What is the best method to use instead of using magic numbers in code?
source share