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

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
sedlalu2
  • 23
  • 3
  • 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. – MSalters Feb 28 '18 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. – molbdnilo Feb 28 '18 at 12:46
  • @molbdnilo: Indeed. But since `static_cast(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. – MSalters Feb 28 '18 at 15:39
  • I know that this code is bad but I was just curious why this happens. Thank you! – sedlalu2 Mar 01 '18 at 07:50

0 Answers0