Home > Mobile >  Is there a way to zero initialize a struct that is compatible between C and C
Is there a way to zero initialize a struct that is compatible between C and C

Time:03-05

Problem: I would like to write a code sample that is cross-compatible between C and C .

I have a plain ol' data (POD) struct like this for example...

typedef struct blob {
    int size;
    uint8_t * data;
} blob;

Is there a simple way to zero initialize this that is valid in both C and C ?

If I understand correctly, the following initializers are not valid in both languages:

blob b = {0}; // valid C, invalid C  
blob b = {}; // valid C  , invalid C

The best I've found so far is:

blob b = {0,0};

... which is okay, but the real struct has 8 fields and that's getting into typo territory.

Question: Is there a common convention used, or a cross-compatible way of initialization that doesn't require knowledge of the fields?

CodePudding user response:

This declaration

blob b = {0};

is valid in both C and C .

If the C compiler supports the C 20 Standard then you can also write

blob b = { .size = 0, .data = 0 };

CodePudding user response:

OK, macros are the spawn of the devil, but would this be of any interest?

#ifdef __cplusplus
    #define ZERO_INIT_MACRO {}
#else
    #define ZERO_INIT_MACRO {0}
#endif

...

blob b = ZERO_INIT_MACRO;

Or is such trickery a bit too naughty in tutorial code?

  • Related