1

I am a bit curious why my code prints a number instead of bool value.

class fb { public: bool p; void func() { memset(&(p), 4, 1); } }; int main() { fb f; f.func(); std::cout << f.p << std::endl; return 0; } 

My code prints number "4" and I am not really sure why this happens. Can you please explain me what is wrong with my code? I was expecting that result will be "true".

Thank you

4
  • 2
    Not sure if it's an exact duplicate, as the code in this question exhibits Undefined Behavior. Here the result "purple" would also have been valid. You can't assume a particular bit pattern for bool. You can memcpy them, doesn't mean you can memset them. Commented Feb 28, 2018 at 12:40
  • Ignoring the undefinedness of the code, memset's second parameter is the value, the third is the number of bytes to set to that value. Commented Feb 28, 2018 at 12:46
  • @molbdnilo: Indeed. But since static_cast<bool>(4)==true, and sizeof(bool) might be 1, I'm not sure if that is an actual mistake. This is just bad code by any standard. Commented Feb 28, 2018 at 15:39
  • I know that this code is bad but I was just curious why this happens. Thank you! Commented Mar 1, 2018 at 7:50

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.