+ 3
Is ~ equal to ! ?
bool a = true; bool b = false; bool c = ~(a && b); //!(a&&b) cout << c;
1 ответ
+ 4
They are different, the ~ operator is a bitwise operator, while ! is a logical operator. The ~ operator is used to invert all the bits of a number, the ! operator tests whether a value or an expression evaluates to true/false.
(a && b) is a logical (boolean) expression, in this case (true && false) evaluates to false, which is zero (for C++). When zero is inverted the value becomes -1 (minus one), but since you assign the result into a bool type, it is assumed as true (1). Any non zero value assigned to a bool type will be stored as true (1).
To see how these operators yields different results, print the result casted as int, as follows:
bool a = true;
bool b = false;
bool c = ~(a && b);
bool d = !(a && b);
cout << c << " " << d; // output: 1 1
cout << (int)~(a && b) << " " << (int)!(a && b); // output: -1 1
Hth, cmiiw