This post is older than 2 years and might not be relevant anymore
More Info: Consider searching for newer posts
This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

Initializing structs with memset

Why is it a standard in nordic-supplied code to initialize structs with memset like so? An example would be:

ble_gatts_char_md_t char_md;
memset(&char_md, 0, sizeof(char_md));

Instead of a cleaner way:

ble_gatts_char_md_t char_md = {0};

I understand that using memset also clears padding bits, but don't understand the reason for doing so.

  • Well there's style, and space.

    ble_gatts_char_md_t char_md = {};
    

    forces the compiler to emit code to explicitly set each element of the structure to zero when it's created, for large structures that's a fair amount of instructions. memset, which is usually linked in anyway, is just a function call, less code space.

  • I don't think that is quite true.

    The {0} version will create a binary version of the structure and the = will cause a copy.

    xx = {0};
    

    is eqivalent to

    y = {0};memcpy(&x,&y, sizeof(y));
    

    ;

    But the result is the same: The code is larger (and slower) since making a large structure needs to make the huge structure then also do a copy. A copy requires reading then writing each word in the structure. That is slower than just setting it to zero.

  • Just did a little experiment with this. There was no change in code size between the two approaches using Keil uVision (armcc).

Related