Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

memseting a struct to zero has always been and still is implementation defined behavior, as there are no guarantees on the bit representation of a null pointer.

The number of bits in a char has also been implementation defined, yet most if not all code either doesn't care, or assumes it to be 8. This is another one of those "in theory, theory and practice are the same; in practice, they're not" things.



N.B. nonzero bitpattern nullptrs are common in C++ for pointer-to-member s, which are typically implemented as an offset from the start of the structure - with an all-0 bitpattern being a valid non-null pointer to the first member of said structure.

    struct S { int i; };
    int S::*a = &S::i;   // probably  0 under the hood
    int S::*b = nullptr; // probably -1 under the hood
    int S::*c = 0;       // probably -1 under the hood (no typo!)
Consider using brace initializers as an ergonomic alternative:

    struct S d = { 0 };
    struct S e = {}; /* as of C23 or C++ */


That's exactly the point of "implementation defined". The code is fine on all those compilers/architectures where the expectation is valid. It just isn't portable to those exotic/hypothetical architectures where it doesn't, which apparently doesn't bother you in your practice. Nothing wrong with that.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: