Is it safe to memset bool to 0?

前端 未结 4 2030
暖寄归人
暖寄归人 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:36

    No. It is not safe (or more specifically, portable). However, it likely works by virtue of the fact that your typical implementation will:

    1. use 0 to represent a boolean (actually, the C++ specification requires it)
    2. generate an array of elements that memset() can deal with.

    However, best practice would dictate using bool data[32] = {false} - additionally, this will likely free the compiler up to internally represent the structure differently - since using memset() could result in it generating a 32 byte array of values rather than, say, a single 4 byte that will fit nicely within your average CPU register.

提交回复
热议问题