8 years, 1 month ago.

What is the initial value of variables in union?

For below decleration;

static union {
    uint64_t hello;
    uint8_t arr[8];
} counter;

counter.hello = 4596545454;

what is the values of unused bytes of array? Zero or random?

1 Answer

8 years, 1 month ago.

The general answer to your question is random. In c all variables are undefined until explicitly set to a value.

For the specific code above there are no undefined values.

hello is a 64 bit value. arr is 8 8 bit values. 8*8 = 64.

Since arr is exactly the same size as hello as soon as you assign a value to hello every value in the array is also defined.

Accepted Answer

This is true, but nowaday, most embedded C compilers will initialize uninitialized variables to 0. But you should not count on this: this behavior may depend on the compiler and/or the linker configuration.

posted by Maxime TEISSIER 29 Mar 2016

Also most embedded memory will be 0 on power up. Which means that even if the compiler doesn't initialize the memory it may well be 0 most of the time.

I've seen a temperature dependent software bug caused by this, at room temperature the memory powered up at all 0 and things worked. At -10 C the memory powered up with a few 1's in it and the software crashed on startup.

Which takes us back to the original point, always assume a variable is random junk unless explicitly initialized.

posted by Andy A 29 Mar 2016