Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preferred way to compare a structure to zero

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:

  1. compare each element to zero, resulting 40 if statements.
  2. allocating a similar structure which is allready zeroed and memcmp it with the structure.
  3. wrapping the structure in a union with a type big enough to cover all of it.

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.

like image 308
stdcall Avatar asked Jan 23 '12 18:01

stdcall


1 Answers

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?

like image 146
ouah Avatar answered Nov 15 '22 17:11

ouah