Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
430 views
in Technique[技术] by (71.8m points)

c++ - Is it safe to memset bool to 0?

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

bool data[32];
memset(data, 0, sizeof(data));

Is this a safe way to set all bool in the array to a false value?

More generally, is it safe to memset a bool to 0 in order to make its value false?

Is it guaranteed to work on all compilers? Or do I to request a fix?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...