What boolean value does an assignment operation implicitly evaluate to in C? - c++

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.

Related

Checking container size in same "if" statement as reading from it

Let's say I have a vector of unknown length.
I want to check if there is a value at vector[3] that is equal to x.
I have to first check if the vector has a length of at least 4.
if(vector.length()>=4)
{
if(vector.at(3) == x)
// Do something
}
My question is: Is it correct to write the same code like this:
if(vector.length()>=4 && vector.at(3) == x)
// Do something
?
Yes, these are equivalent.
The logical AND operator && has what is referred to as short circuit behavior. If the left operand evaluates to false (i.e. 0) then the entire expression is false and the right operand is not evaluated.

Assignment in an 'if' statement. How is the output correct?

Code in case if the image not is visible.
#include <stdio.h>
int fun(int n)
{
if(n=4)
return n;
else
return 2*fun(n+1);
}
int main()
{
printf("%d", fun(2));
}
This is the code snippet and the output is given as 4 by the professor.
How is the output correct?
Is it possible that n=4 is assigned in the 'if-else' statement as the assignment operator is correct, but the "if" condition will not work as the syntax is wrong and the output will be directly given as 4.
The answer is correct, and there aren't any syntax errors.
= is an assignment operator, and in C/C++, (n = 4) is a valid expression that evaluates to true as long as the expression is not (n = 0), because n will then be considered as false by C. Note that in C/C++, 0 is false and everything else is true.
Hence, if (n = 4) is perfectly valid and always evaluates to true. Of course, in the process, there will also be an assignment involved.
Thus, what happens in the code above is that
the integer n is assigned the value 4 in n = 4
(n=4) as an expression returns true.
return n (4).
So the answer is 4.
Assignment in a if-else statement is valid syntax and the branching will depend on the value of n.
Example:
#include <iostream>
int main() {
int n = 2;
if (n = 0) {
std::cout << "Never printed\n";
}
if (n = 4) {
std::cout << "Always printed\n";
}
return 0;
}
Compiler explorer: https://godbolt.org/z/fEYPcq
You should use == operator to make a confront between two compatible values.
if(n = 4) assign 4 to n and then the if statement is always true. So the return value will always be 4.
"Is it possible that n = 4 is assigned in the if-else statement as the assignment operator is correct, but the if condition will not work as the syntax is wrong....?"
The syntax is not wrong and the if condition does work. It is perfectly valid. And yes, the assignment is also valid/correct.
With if (n = 4) you assign the value of 4 to the function-local variable n, although this makes less sense since n is a parameter and is meant to be feed with different values at each call to the function fun().
But I guess the intention of your professor is exactly to demonstrate this trickery, so it makes sense.
So the value of n is not 2 anymore; It is 4.
This is a valid expression for the if condition and evaluates to 1/true since the value/expression to be assigned is or does not evaluate not 0.
Usually a compiler will warn you about doing so nonetheless to avoid any undesired result here by suggesting optional parentheses around the assignment like: if ((n = 4)).
Clang:
warning: using the result of an assignment as a condition without parentheses [-Wparentheses]
GCC:
warning: suggest parentheses around assignment used as truth value [-Wparentheses]
If you explicitly want to remove these warnings, use the -Wno-parentheses flag. But it is recommended not to do so.
Since the if condition is true, it doesn't get to the recursive part in the else condition and the function fun immediately returns n which is 4.
So is the return value of 4 displayed by the call to printf() in the caller.
My favorite to remember that is this:
int war = false;
if (war = true) { launch nuke; }
Credits go to WTP.
Maybe you'll catch the joke. ;-)

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.

Ternary operator with no condition

I found a section of code that shows the following:
int A = 4;
int Z;
Z = (A ? 55 : 3);
Why does the result for Z give 55?
You seem to have a common misconception about the fact that expressions in conditional statements (if, while, ...) and ternary operations must "look like" a condition, so they should contain a relational/equality/logical operator.
It's not like that. Commonly used relational/equality/... operators don't have any particular relationship with conditional statements/expressions; they can live on their own
bool foo = 5 > 4;
std::cout<<foo<<"\n"; // prints 1
and conditional statements/expressions don't care particularly for them
if(5) std::cout << "hello\n"; // prints hello
if/?/while/... just evaluate the expression, check if the result, converted to bool, is true or false, and act accordingly. If the expression doesn't "looks like" a condition is irrelevant, as long as the result can be converted to bool you can use it in a conditional.
Now, in this particular case A evaluates to 4, which is not zero, so when converted to bool is true, hence the ternary expression evaluates to its second expression, so 55.

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.