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.
Related
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.
This question already has answers here:
What is !0 in C?
(5 answers)
Closed 3 years ago.
I was doing some random stuff and I came up with int a = !3; and when I outputted the value it I was expecting an error but it got me a 0.
Why did this happen and what ! means on that example?
! is the BOOLEAN NOT operator, i.e. !true == false and !false == true. In C and C++ every value that is nonzero is treated as true when used with a boolean operator. And false is numerically 0. So 3 is treated as true and !3 = !true = false = 0.
!3 is an expression, it evaluates to a bool type.
In this example it evaluates to false.
bool's can be casted to an int, which happens automatically when you assign it to one.
The int representation of false is '0' whilst true is '1'.
That "negates" the value. Anything non-zero becomes 0, and 0 becomes 1.
This question already has answers here:
How is if statement evaluated in c++?
(7 answers)
Closed 7 years ago.
What does this condition mean in a while loop?
int x;
cin >> x;
while(x) {
...
}
int has an implicit conversion to bool. Basically 0 converts to false, all nonzero values convert to true
So more verbosely, your condition would read
while (x != 0)
As #CoryKramer says, when you have a condition which only contains a variable, even if is a char, int, float, etc. the value 0 is considered as false, and any other as true. If you are using pointers is the same: the NULL value is considered as false, and any other direction is considered as true.
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.
I stumbled across this code recently:
void strcat( char* dest, char* src )
{
while (*dest) dest++;
while (*dest++ = *src++);
}
Where it looks like the *dest++ = *src++ operation is being used as a condition for the while loop. How is this assignment operation converted to boolean? I'm having a hard time understanding it.
Furthermore, is the same syntax valid in C++?
In C, a non-zero value in a logical statement counts as a true, zero as false.
And the result of any assignment statement is the value of the left operand after the assignment.
And so in the second loop, if the value assigned is 0, the result of the condition is false. In the first loop, if the value of the pointed-to variable itself is 0, the condition is false.
This syntax is also valid in C++.
What boolean value does an assignment operation implicitly evaluate to in C?
An assignment operation evaluates to the variable being assigned (left hand side):
int i = 0;
int j = (i = i+5); // j == 5 | (i = i+5) assigns 5, then evaluates to i
Now, when used as a condition, an integral value evaluates to true when it is non-zero or to false if it is zero.
An expression that evaluates to 0 is false.
An expression that evaluates to non-zero is true.
When *dest equal 0, the first while loop will terminate.
Similarly with the second.