Can I use the not operator in C++ on int values? - c++

Strange question, but someone showed me this,
I was wondering can you use the not ! operator for int in C++? (its strange to me).
#include <iostream>
using namespace std;
int main()
{
int a=5, b=4, c=4, d;
d = !( a > b && b <= c) || a > c && !b;
cout << d;
system ("pause");
return 0;
}

Yes. For integral types, ! returns true if the operand is zero, and false otherwise.
So !b here just means b == 0.
This is a particular case where a value is converted to a bool. The !b can be viewed as !((bool)b) so the question is what is the "truthness" of b. In C++, arithmetic types, pointer types and enum can be converted to bool. When the value is 0 or null, the result is false, otherwise it is true (C++ ยง4.1.2).
Of course custom classes can even overload the operator! or operator<types can be convert to bool> to allow the !b for their classes. For instance, std::stream has overloaded the operator! and operator void* for checking the failbit, so that idioms like
while (std::cin >> x) { // <-- conversion to bool needed here
...
can be used.
(But your code !( a > b && b <= c) || a > c && !b is just cryptic.)

Originally, in C (on which C++ is based) there was no Boolean type. Instead, the value "true" was assigned to any non-zero value and the value "false" was assigned to anything which evaluates to zero. This behavior still exists in C++. So for an int x, the expressions !x means "x not true", which is "x not non-zero", i.e. it's true if x is zero.

You can, !b is equivalent to (b == 0).

The test for int is true for non-zero values and false for zero values, so not is just true for zero values and false for non-zero values.

The build-in ! operator converts its argument to bool. The standard specifies that there exists a conversion from any arithmetic type(int, char,.... float, double...) to bool. If the source value is 0 the result is true, otherwise it is false

Related

AND Operation for -1

While implementing logical operations in the code, I discovered a phenomenon where it should not be entered in the if statement.
It turns out that this is the AND (&&) operation of -1 and natural numbers.
I don't know why the value 1 is printed in the same code below.
I ran direct calculations such as 1's complement and 2's complement, but no 1 came out.
#include <iostream>
using namespace std;
int main()
{
int a = 10;
int b = -1;
int c = a && b;
printf("test = %d",c);
return 0;
}
The expression a && b is a bool type and is either true or false: it is true if and only if both a and b are non-zero, and false otherwise. As your question mentions complementing schemes (note that from C++20, an int is always 2's complement), -0 and +0 are both zero for the purpose of &&.
When assigned to the int type c, that bool type is converted implicitly to either 0 (if false) or 1 (if true).
(In C the analysis is similar except that a && b is an int type, and the implicit conversion therefore does not take place.)

Using enum as a condition, what will the if condition return, True or False?

enum segment
{
OFF,
ON
};
int main()
{
segment indicator;
int temp_prev = 37;
int temp_curr = 39;
indicator = OFF;
if ((temp_curr > temp_prev and temp_curr > 39) or !indicator)
{}
This is part of a basic program to understand the use and properties of enum.
What confuses me is, what does !enum return, and what will the if condition return?
(Assuming C) An enum is stored as an int. In your example, OFF would default to zero, which is treated as false in a conditional, any non-zero value would be considered true.
what confuses me is what does !enum return
Unary ! is the logical NOT operator. The enum value implicitly converts to the underlying integer type. The result is true if that integer is 0, and false otherwise. The underlying value of OFF is 0, therefore the result is true in this case, and so is the entire condition.

while loop with unsigned integer condition [duplicate]

This question already has answers here:
How is if statement evaluated in c++?
(7 answers)
Closed 5 years ago.
I'm not sure how the while loop works in the following simple piece of code
short CountBits(unsigned int x){
short num_bits = 0;
while (x){
num_bits += x & 1;
x >>= 1;
}
return num_bits;
}
How does an unsigned integer evaluate to True or False?
In the given context, x must be converted to true or false.
From the C++11 Standard (4.12/1):
A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true.
Think of
while (x){ ... }
as
while (x != 0){ ... }
True is any integer which is not equal to 0. Thus if x evaluates to 0 then the loop breaks.
"How does an unsigned integer evaluate to True or False"? The same way any numeric value evaluates to true or false: 0 is false, any other value is true. Some people would write the test as while (x != 0); that's exactly the same thing.
For any integral number in C++, on most machines, 0 will evaluate to false. As such, when X becomes 0, the loop will terminate. The loop will continue while x is a non-zero value.

Is it safe to compare boolean variable with 1 and 0 in C, C++? [duplicate]

This question already has answers here:
Can I assume (bool)true == (int)1 for any C++ compiler?
(5 answers)
Closed 8 years ago.
Consider the code
bool f() { return 42; }
if (f() == 1)
printf("hello");
Does C (C99+ with stdbool.h) and C++ standards guarantee that "hello" will printed? Does
bool a = x;
is always equivalent to
bool a = x ? 1 : 0;
Yes. You are missing a step though. "0" is false and every other int is true, but f() always returns true ("1"). It doesn't return 42, the casting occurs in "return 42;".
In C macro bool (we are speaking about the macro defined in stdbool.h) expands to _Bool that has only two values 0 and 1.
In C++ the value of f() in expression f() == 1 is implicitly converted to int 1 according to the integral promotion.
So in my opinion this code
bool f() { return 42; }
if (f() == 1)
printf("hello");
is safe.
In C++, bool is a built-in type. Conversions from any type to bool always yield false (0) or true (1).
Prior to the 1999 ISO C standard, C did not have a built-in Boolean type. It was (and still is) common for programmers to define their own Boolean types, for example:
typedef int BOOL;
#define FALSE 0
#define TRUE 1
or
typedef enum { false, true } bool;
Any such type is at least 1 byte in size, and can store values other than 0 or 1, so equality comparisons to 0 or 1 are potentially unsafe.
C99 added a built-in type _Bool, with conversion semantics similar to those for bool in C++; it can also be referred to as bool if you have #include <stdbool.h>.
In either C or C++, code whose behavior is undefined can potentially store a value other than 0 or 1 in a bool object. For example, this:
bool b;
*(char*)&b = 2;
will (probably) store the value 2 in b, but a C++ compiler may assume that its value is either 0 or 1; a comparison like b == 0 or b == true may either succeed or fail.
My advice:
Don't write code that stores strange values in bool objects.
Don't compare bool values for equality or inequality to 0, 1, false, or true.
In your example:
bool f() { return 42; }
Assuming this is either C++ or C with <stdbool.h>, this function will return true or, equivalently, 1, since the conversion of 42 to bool yields 1.
if (f() == 1)
printf("hello");
Since you haven't constructed any strange bool values, this is well behaved and will print "hello".
But there's no point in making the comparison explicitly. f() is already of type bool, so it's already usable as a condition. You can (and probably should) just write:
if (f())
printf("hello");
Writing f() == 1 is no more helpful than writing (f() == 1) == 1).
In a real program, presumably you'll have given your function a meaningful name that makes it clear that its value represents a condition:
if (greeting_required())
printf("hello");
The only real trick that I know of, that is useful with pre-C99 environments is the double negation
int a = 42;
if ( (!!a) != 0 ) printf("Hello\n");
this will print Hello because the result of the !! operation is a boolean that is true when the value is non-zero, false otherwise. But this is gonna cost you 2 negation to get the boolean that you want, in modern standards this is redundant because you will get the same result without the !! and it's a result granted by the language.

C++ Boolean Algebra

I have declared some variable as Boolean and I was hoping that C++ would know what to do when I did some boolean addition but it's not happening the way I would like it to. How do I get it to work.
#include<iostream>
using namespace std;
int main()
{
bool x,j;
x=0;
j=1;
for(int i=0;i<10;i++)
{
cout << x;
x=x+j;
}
return 0;
}
I am getting the output as
011111111
whereas I was hoping to get
0101010101
I was hoping that Boolean variables would mod out by 2. So if
x=1 then
x+1 = 0
x+1+1=1
x+1+1+1=0
and so on.
Am I confusing boolean algebra with base-2 algebra?
Thanks
bool x,j;
x=x+j;
This statement automatically promotes x and j to type int before adding them. Then the assignment converts back to bool in the usual way: 0 becomes false, but any other number , including 2, becomes true.
You can get Z_2 addition by using the ^ (xor) operator instead:
x = x^j;
C/C++ provide a range of bitwise operators: &, |, ^, ~, which generally work on booleans because true is converted to the integer 1 and false to 0.
But you can also use real boolean operators:
&& conjunction
|| disjunction
!= exclusive or (what you regard as addition)
! not