Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

235
Views
Is there a way to zero initialize a struct that is compatible between C and C++

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?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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

#ifdef __cplusplus
    #define ZERO_INIT
#else
    #define ZERO_INIT 0
#endif

...

blob b = {ZERO_INIT};

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

(Edited to reflect suggestions in the comments).

over 4 years ago · Santiago Trujillo Report

0

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 };
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!