PowerBasic Museum 2020-A

IT-Consultant: Patrice Terrier => C++ programming (SDK style) => Topic started by: Patrice Terrier on February 01, 2020, 10:28:20 AM

Title: C - Unions
Post by: Patrice Terrier on February 01, 2020, 10:28:20 AM
TIP (from Michael Lobko-Lobanovsky)
A c/C++ union is a special data type that allows to store different data types in the same memory location.
You can define a union with many members like in the example below

struct BINBOOL {
    union {
        struct {
            unsigned bGiration: 1; // type name: size in bits = initialization
            unsigned bUseFPS: 1;
            unsigned bAnimate: 1;
            unsigned bRotation: 1;
            unsigned bIsLerping: 1;
            unsigned bSyncAudio: 1;
            unsigned bUnused: 26; // currently unused
        };
        unsigned reDraw;
    }; // initialization
};
static BINBOOL gB;

This give us 32 bit (0 or 1) that we could use as boolean flags

and rather than using this complex if comparison:

if (gB.bGiration || gB.bUseFPS || gB.bAnimate || gB.bRotation || gB.bIsLerping || gB.bSyncAudio) {
    Redraw();
}


we can just use this short syntax, and fastest comparison.

if (gB.reDraw) ( Redraw(); )

and the whole size of BINBOOL is only 4-bytes.