I am currently using static const in my code instead of using 'magic numbers'as mentioned in "static const" vs "#define" vs "enum".
void checkInvalidResponse (uint8_t response)
{
static const uint8_t INVALID_RESP = 0xFF;
if (response == INVALID_RESP)
{
/* Code for invalid response */
}
}
I, however, think that using static const would consume memory in the compiled code for INVALID_RESP. The statement would also translate to machine code that does a LOAD from the memory followed by the compare, instead of comparing with a value provided as part of the instruction. Is this correct? If so, then this solution would not be optimal in terms of speed and memory right?
I am currently changing the code to use #defines
void checkInvalidResponse (uint8_t response)
{
#define INVALID_RESP 0xFF
if (response == INVALID_RESP)
{
/* Code for invalid response */
}
}
However, since #define does not have a scope, would the behavior of the cut-and-paste aspect of #define be consistent across multiple compilers? For example, if INVALID_RESP is re-defined later, would any code in lines following the redefinition use the new value?
Another approach I have looked at is to use enumerations.
void checkInvalidResponse (uint8_t response)
{
typedef enum
{
INVALID_RESP = 0xFF
} resp_t;
if ((resp_t)response == INVALID_RESP)
{
/* Code for invalid response */
}
}
However, the typecasting to an enum would allocate more memory than needed (The processor would do a 32 bit(?) compare instead of an 8 bit compare).
What is the best method to use instead of using magic numbers in code?