Zeroing Entity ?

In handmade.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
internal uint32
AddEntity(game_state *GameState)
{
    uint32 EntityIndex = GameState->EntityCount++;

    Assert(GameState->EntityCount < ArrayCount(GameState->Entities));
    entity *Entity = &GameState->Entities[EntityIndex];
    *Entity = {};
    return(EntityIndex);
}


If I'm not mistaken, every time we add a new entity we are supposed to zero the struct values to zero, with:

1
*Entity = {};


But in my case it is not really working: if I break after that line, the Entity structure pointed has still values != 0, which cause an additional fake player to be drawn.

This happen in my own version of the code, so I might have missed something, but my question is: is using the empty braces supposed to work, in order to zero a struct after declaration?

I have found examples where it is used in the same line where we declare the struct, but none where it is used afterwards.

If I use a memset to zero, instead of the braces, it works.

Edited by Vincenzo Auteri on
Do you happen to have nested structures inside your Entity? If yes, those will not get nulled recursively.
Oops, I actually was setting a value for facingDirection inside the struct declaration itself.

1
2
3
4
5
6
7
8
struct Entity{
    bool32 exists;
    TileMapPosition position;
    V2 dP;
    float width;
    float height;
    uint32_t facingDirection = 0;
}


For some reason, the side effect is what I described. If I remove it, it works.

Thanks.
Yeah, this is C++11 thing. If you use member initialiation like this, then C++ compiler generates default constructor that initializes memebers you specified, but not others. And when you use {} syntax, then compiler calls this constructor.

Somebody else had exactly same problem here: https://forums.handmadehero.org/i...p/forum?view=topic&catid=4&id=242
Understood.

It makes sense, I guess, since you might want to init only particular values, and don't care for other ones.

With C++ you learn something new every day :cheer:

Thanks everybody.