Is it safe to memset bool to 0?

前端 未结 4 2025
暖寄归人
暖寄归人 2020-12-01 13:56

Suppose I have some legacy code which cannot be changed unless a bug is discovered, and it contains this code:

bool data[32         


        
4条回答
  •  忘掉有多难
    2020-12-01 14:20

    Is it guaranteed by the law? No.

    C++ says nothing about the representation of bool values.

    Is it guaranteed by practical reality? Yes.

    I mean, if you wish to find a C++ implementation that does not represent boolean false as a sequence of zeroes, I shall wish you luck. Given that false must implicitly convert to 0, and true must implicitly convert to 1, and 0 must implicitly convert to false, and non-0 must implicitly convert to true … well, you'd be silly to implement it any other way.

    Whether that means it's "safe" is for you to decide.

    I don't usually say this, but if I were in your situation I would be happy to let this slide. If you're really concerned, you can add a test executable to your distributable to validate the precondition on each target platform before installing the real project.

提交回复
热议问题