Today I came across a situation where I needed to decide if an entire structure that consists of about 40 elements is zero - meaning that each of the elements is zero.
When thinking how to make it as fast and efficient as possible, I thought of 3 different ways to do so:
memcmp
it with the structure.for instance
typedef union {
struct {
uint8_t a;
uint8_t b;
}
uint16_t c;
} STRUCTURE_A;
and then comparing it to zero.
I would like to know what you think about these solutions, which of them you find the fastest and the most efficient.
And if you thing of a better approach please tell me...
Thanks.
Compare every member of the structure to 0.
This is the only safe way to compare two structures objects (even if one of the structure objects has all members set to the value 0). Don't use memcmp
to compare a struct, the value of the padding's bytes in the structure is unspecified. Note also that it is not permitted to use the ==
operator with structure objects operands.
See this c-faq link on structure object comparison:
Q: Is there a way to compare structures automatically?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With