Handmade Hero»Forums»Code
Vincenzo Auteri
6 posts
Zeroing Entity ?
Edited by Vincenzo Auteri on
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.
Benjamin Kloster
48 posts
Zeroing Entity ?
Do you happen to have nested structures inside your Entity? If yes, those will not get nulled recursively.
Vincenzo Auteri
6 posts
Zeroing Entity ?
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.
Ville Penttinen
8 posts
Zeroing Entity ?
Most likely this is due to http://en.cppreference.com/w/cpp/language/aggregate_initialization
Mārtiņš Možeiko
2562 posts / 2 projects
Zeroing Entity ?
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
Vincenzo Auteri
6 posts
Zeroing Entity ?
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.