Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

249
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda