5

I have a struct with an unsigned char[16] field that I'd like to initialize to zeros. The following (strongly simplified) code compiles fine with clang (OS X):

struct GUID {
    unsigned char bytes[16];
    GUID() : bytes("\0\0\0\0""\0\0\0\0""\0\0\0\0""\0\0\0") {};
}

Note I use 15 \0s because the 16th is the zero terminator of the string literal, and clang complains if you initialize a string with too many bytes.

Now, when I try to compile with GCC 4.5.3 (cygwin), I get:

error: incompatible types in assignment of 'const char [16]' to 'unsigned char [16]'

Why doesn't it work, and how can I make it work? (I could obviously loop through the array in the constructor, but I'd like to use the initialization list if possible, and I'd like to understand why it works in one compiler, but not the other.)

0

3 Answers 3

2

A simple bytes() should be sufficient in this case. You could also consider bytes { 0,0,0,0.... }.

Also, use std::array, not T[]. Only fools use T[] when they could use std::array.

Sign up to request clarification or add additional context in comments.

Comments

2

Since we're dealing with POD its sufficient to explicitly construct bytes, which will result in the corresponding memory being 'zeroed':

struct GUID 
{
    unsigned char bytes[16];
    GUID() : bytes(){}
};

It's probably worth noting that if you didn't explicitly construct bytes in the initialization list, it would be left uninitialized

struct GUID 
{
    unsigned char bytes[16];
    GUID(){};
};

If the member variable were not a POD but instead a member object then instead of being left uninitialized it would call its default constructor.

Comments

1

In the GUID constructor you can use memset(bytes, 0, sizeof(bytes));

4 Comments

Right, that's probably the cleanest solution and what I'll do.
No, for your particular case, the best solution is the one by DeadMG.
@Haroogan: Is the array guaranteed to be filled with zeros if I do bytes()?
Yes, it is. That's what DeadMG told you, basically.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.