What is this declaration doing in C++? C++14
unsigned char Mem[0x1000] {0};
unsigned char Mem[0x1000] {0};
It creates an array of 0x1000 elements, and initializes it using the initializer {0}
. That sets the first element to 0
and then value-initializes the remaining elements, which sets them to 0
as well.
i.e. it's identical to this, which just value-initializes every element:
unsigned char Mem[0x1000] {};
That's also identical to saying ={}, except that before C++11 it was only possible to use the ={} form, now you can also use {} without the =
For this case:
unsigned char Mem[0x1000] {0x12, 0x00};
it sets the first element to 0x12
, then the second element to 0x00
, then sets the remainder to 0
. i.e. it's the same as:
unsigned char Mem[0x1000] {0x12};
If every element is being filled with a zero, why do that?
In C you can't have an empty initializer, so you can't say {}
and have to do {0}
. That's not true in C++, so there's no reason to prefer {0}
to {}
when they do the same thing.
Do i need to "clean" every variable I declare?
If you don't use any initializer then the elements will be uninitialized, so have indeterminate values, and reading an element before you've assigned a value to it would be undefined behaviour.