Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

244
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda