Friday, 15 July 2011

c++ - How to instantly check the zero value of a structure without checking its each element? -



c++ - How to instantly check the zero value of a structure without checking its each element? -

suppose have byte structure, :

struct one_byte { char b1 : 1, b2 : 1, b3 : 1, b4 : 1, b5 : 1, b6 : 1, b7 : 1, b8 : 1; }foo;

in cases i'll need check (foo == 0), have 8 commands :

if(foo.b1 == 0 && foo.b2 == 0 && foo.b3 == 0 && ...and on

is there portable & convenient way can instantly check 0 value single command? tried functions & templates, perform slowly. , tried union, compiler doesn't back upwards bit[array]....

use union, intended for

union { struct { char b1:1,b2:1,b3:1,b4:1,b5:1,b6:1,b7:1,b8:1; } bits; unsigned char byte; } u;

then can either assign straight byte

u.byte = 15;

or bits individually

u.bits.b3 = 1;

exemple

int main() { u.byte = 0; printf("%x\n", u.byte); u.bits.b3 = 1; u.bits.b4 = 1; printf("%x\n", u.byte); homecoming 0; }

will output

0 c // 12 in decimal, since b3 , b4 set 1

c++ performance structure zero

No comments:

Post a Comment