Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does bool and not bool both return true in this case? [duplicate]

Tags:

c++

boolean

This is my code:

#include <cstring> #include <iostream> int main() {     bool a;     memset(&a, 0x03, sizeof(bool));     if (a) {         std::cout << "a is true!" << std::endl;     }     if (!a) {         std::cout << "!a is true!" << std::endl;     } } 

It outputs:

a is true! !a is true! 

It seems that the ! operator on bool only inverts the last bit, but every value that does not equal 0 is treated as true. This leads to the shown behavior, which is logically wrong. Is that a fault in the implementation, or does the specification allow this? Note that the memset can be omitted, and the behavior would probably be the same because a contains memory garbage.

I'm on gcc 4.4.5, other compilers might do it differently.

like image 356
flyx Avatar asked Apr 24 '14 12:04

flyx


People also ask

Is bool automatically true?

bool "bar" is by default true, but it should be false, it can not be initiliazied in the constructor. is there a way to init it as false without making it static?

Is bool One True or false?

A true boolean data type could be used for storing logical values, and would only have two legal values - "true", and "false". C does not have boolean data types, and normally uses integers for boolean testing. Zero is used to represent false, and One is used to represent true.

What is the parent type of int and bool?

True and False are instances of bool and therefore instances of the parent class int , but bool itself is not an instance of int . Being a class it's an instance of type and a subclass of int .

Is negative 1 true in Python?

Numbers. In Python, the integer 0 is always False , while every other number, including negative numbers, are True .


1 Answers

The standard (3.9.1/6 Fundamental types) says:

Values of type bool are either true or false.

....

Using a bool value in ways described by this International Standard as “undefined,” such as by examining the value of an uninitialized automatic object, might cause it to behave as if it is neither true nor false.

Your program's use of memset leads to undefined behaviour. The consequence of which might be that the value is neither true nor false.

like image 168
David Heffernan Avatar answered Oct 21 '22 16:10

David Heffernan