C++ random bitwise behavior - c++

INTENTION -> A program that adds even numbers only within a range
Strange behavior -> the logical statement is incorrect for adding even numbers, instead the logical statement is correct for adding odd numbers, but the sum of even numbers is the result. As we all know, num & 1 returns true if num is odd, and false if num is even.
Question -> Check my logical statement in the code. Why is the increment of n inline with the logical operator inverting the return value and summing even numbers (which is intended, but unexpected for this logical statement)?
//program to print sum of even numbers
#include <iostream>
int main(){
int n = {0}, result = {0};
while(n < 99) result += n++ & 1 ? n : 0;
std::cout << result << '\n';
}
I was experiencing some random behavior when attempting a simple coding implementation of a bitwise odd number detection. num & 1
This is returning the desired and appropriate value of even nums between 0 and 100, when I'm not using any negation. such as ~num & 1 . Can someone explain to me why the negation isn't necessary, and why its returning even values? Is there some extra behavior to the n++ happening?
NOTE: I understand the syntax is obtuse, that was sort of my intention, to be as obtuse as possible for the sake of experimenting with the language a bit. I'm not asking for a style critique.
Examples
https://repl.it/KG8Z/1 < this should print odd, but what is the unintended side-effect of the ++ operator that is making it print even numbers?
https://repl.it/KG8Z/0 < c++
https://repl.it/KGId/3 < python
I was expecting to need to use the bitwise not operator in c++ to get the desired result, but the results are the same despite the absence of a logical not. How to explain this odd behavior?

When
n++ & 1
executes, lets expect n is odd number at the moment, condition is true.
Post incrementation is applied and n is even when
result += n
executes. Thats why its counting even numbers instead of odd. Modify code to
while(n < 99) result += !(n++ & 1) ? n : 0;
and it will count odd one's.

[expr.cond]/1:
Conditional expressions group right-to-left. The first expression is
contextually converted to bool. It is evaluated and if it is true, the
result of the conditional expression is the value of the second
expression, otherwise that of the third expression. Only one of the
second and third expressions is evaluated. Every value computation and
side effect associated with the first expression is sequenced before
every value computation and side effect associated with the second or
third expression.
Thus, n is "selected" on odd ns in the condition, but at that point, it's already incremented (even).
n & ~1 is not the same as !(n & 1).

Related

Why adding "variable + 1" doesn't increment its value by one for every loop in a for loop? (C++)

I'm having a hard time understanding why using a increment operator in a for loop in C++ has a different result than doing 'variable' + 1. The variable in the second case simply isn't remembered after each iteration of the loop:
Take the following code:
#include <iostream>
int main(){
int a{0};
for (int i = 0; i < 5; i++){
std::cout << ++a;
}
return 0;
}
It outputs as expected:
12345
However, if I instead replace ++a with a + 1:
#include <iostream>
int main(){
int a{0};
for (int i = 0; i < 5; i++){
std::cout << a + 1;
}
return 0;
}
I get:
11111
Even if I make the 'a' variable static:
static int a{0};
It still outputs 11111.
Why doesn't 'a + 1' preserve its value after every loop? What would I need to do if I wanted to preserve its value after every iteration without using ++ (for instance, with another operation like a * 2)?
Why doesn't 'a + 1' preserve its value after every loop?
a + 1 is an expression that doesn't assign anything to a. That is a is not affected in any way. This means when you do just a + 1, the value of a is still 0(the old value).
On the other hand ++a has the same effect as:
v---------->assignment done here implicitly
a = a+1
In the above expression ++a, the value of is incremented by 1 so that the new value of a is now 1.
++a is equivalent to the assignment a= a + 1 (or a+= 1). The expression a + 1 alone does not modify a.
C++ will allow you to write std::cout << (a= a + 1);.
a++ is not the same thing as a+1 but as a=a+1.
What's the difference?
Well:
a+1 contains the value, which is one higher than the value of a.
a=a+1 means that, in top of this, this value gets assigned to the variable a, which means something like "replace a by its value plus one".
This gives following possibilities (I also show the difference between a++ and ++a):
int a=3;
cout<<a+1; // output : 4. Value of 'a' equals 3.
cout<<a+1; // output : 4. Value of 'a' equals 3.
cout<<a+1; // output : 4. Value of 'a' equals 3.
int a=3;
cout<<a++; // output : 3. Value of 'a' becomes 4 after having shown it on screen.
cout<<a++; // output : 4. Value of 'a' becomes 5 after having shown it on screen.
cout<<a++; // output : 5. Value of 'a' becomes 6 after having shown it on screen.
int a=3;
cout<<++a; // output : 4. Value of 'a' becomes 4 before showning it on screen.
cout<<++a; // output : 5. Value of 'a' becomes 5 before showning it on screen.
cout<<++a; // output : 6. Value of 'a' becomes 6 before showning it on screen.
Conceptually, the built-in arithmetic operators like + and * evaluate their operands, perform the respective operation with the thusly obtained values, and create a temporary object that contains the result.
The operands, one of which is your a, are only read from, not written to. That is more obvious when you consider that + is commutative, that is, its operands can be swapped without affecting the result: a+1 is by definition the same as 1+a, and clearly you cannot write anything back to the immediate value 1.
Generally, as you certainly know, = is used in C and C++ to write a value to a variable. C, and by means of ancestry also C++, provide shortcuts to write back the result of certain operations to one of their operands: it's the combination of the operator and the assignment =, for example a += 1. Like all assignments, this one is an expression (that is, it has a value) which has the value of the variable after the operation and assignment. Like all other expressions, you can use it as a subexpression, even though that's not very common: cout << (a += 1); would achieve the desired effect (the parentheses are necessary because assignment has about the lowest operator precedence). Because incrementing (and decrementing) by one is so very common, C and C++ have a shortcut for the shortcut: ++a is the same as a+=1, so that one would typically write cout << ++a; (as a side effect obviating the need for parentheses).

C++ Modulus Operator Understanding

I am just starting out programming and reading thru C++ Programming Principles and Practice. I am currently doing the Chapter 3 exercises and do not understand why this code I wrote works. Please help explain.
#include "std_lib_facilities.h"
int main() {
cout<<"Hello, User\n""Please enter a number (Followed by the 'Enter' key):";
int number=0;
cin>> number;
if (number%2) {
cout<<"Your number is an odd number!";
} else {
cout<<"Your number is an even number\n";
}
return 0;
}
When number is odd, number%2 is 1.
if (number%2) {
is equivalent to
if (1) {
Hence, you get the output from the line
cout<<"Your number is an odd number!";
When number is even, number%2 is 0.
if (number%2) {
is equivalent to
if (0) {
Hence, you get the output from the line
cout<<"Your number is an even number\n";
The modulus operator simply determines the remainder of the corresponding division problem. For instance, 2 % 2 returns 0 as 2 / 2 is 1 with a remainder of 0.
In your code, any even number entered will return a 0 as all even numbers are, by definition, divisible by 2 (meaning <any even number> % 2 == 0)
Likewise, any odd number entered will return 1 (for instance, 7 % 2 == 1 as 7 / 2 has a remainder of 1).
In c++, like in many programming languages, numeral values can be treated as booleans such that 0 relates to false while other numbers (depending on the language) relate to true (1 is, as far as I know, universally true no matter the programming language).
In other words, an odd number input would evaluate number % 2 to 1, meaning true. So if (number % 2), we know that the input number is odd. Otherwise, number % 2 must be false, meaning 0, which means that the input number is even.
"if" statements works on boolean values. Let's remember that boolean values are represented by "false" and "true", but in reality, it's all about the binary set of Z2 containing {0, 1}. "false" represents "0" and "true" represents "1" (or some people in electronics interpret them as "off/on")
So, yeah, behind the curtains, "if" statements are looking for 0 or 1. The modulus operator returns the rest of a / b. When you input any number and divide it by 2, you are gonna get a rest of 0 or 1 being it pair or an odd number.
So that's why it works, you will always get a result of 0 or 1 which are false and true by doing that operation that way.
think of modulus in terms of this:
while (integer A is bigger than integer B,)
A = A - B;
return A
for example, 9%2 -> 9-2=7-2=5-2=3-2=1
9%2=1;
the statement if (number%2) is what is called a boolean comparison (true false). Another way to write this statement identically is if(number%2 != 0) or if(number%2 != false) since false and zero are equivocal. You're taking the return value of the modulus operator function (a template object we will assume is an integer) and inserting it into an if statement that executes if the input does not equal zero. If statements execute if the input is -5,9999999,1-- anything but zero. So, if (2) would be true. if(-5) would also be true. if(0) would be false. if(5%2) would be 1 = true. if(4%2) would be if(0) = false. If it is true, the code in the body of the if statement is executed.

What is the difference between && and ||? [duplicate]

This question already has answers here:
Is short-circuiting logical operators mandated? And evaluation order?
(7 answers)
Closed 8 years ago.
I'm getting it difficult to understand how the following programs work, kindly help me in understanding.
int x=2,y=0;
(i)
if(x++ && y++)
cout<<x<<y;
Output:
(ii)
if(y++ || x++)
cout<<x<<" "<<y;
Output: 3 1
(iii)
if(x++||y++)
cout<<x<<" "<<y;
Output: 3 0
Kindly explain me how the program is working and also, what makes the difference between (ii) and (iii).
You are looking at a "C++ puzzle" which is using two languages tricks.
The first is that postincrement uses the value of the variable first, then increments the variable.
So x++ has the value 2 in the expression and then x becomes 3
y++ has the value 0 in the expression, and then y becomes 1
&& is and
|| is or
both operators are short-circuiting.
Look at && first.
In order for and to be true, both sides must be true (non-zero)
Since it is x++ && y++, first the x++ happens, and since it is non-zero (true)
the y++ has to happen to determine whether the result is true or not.
Therefore x is 3 and y is 1.
The second case is the same. y is zero, but in order to determine if the OR is true,
the if statement executes the second half of the expression.
The third case, since it is in the opposite order, never executes y++ because
x++ || y++
the first half being x++, it is already true, so the compiler does not bother to execute the second half of the test.
int x=2,y=0;
Condition in if() is evaluated according to the rules:
operator && evaluates left operand first and if the value is logically false then it avoids evaluating the right operand. Typical use is for example if (x > 0 && k/x < limit) ... that avoids division by zero problems.
operator || evaluates left operand first and if the value is logically true then it avoids evaluating the right operand. For example if (overwrite_files || confirm("File existing, overwrite?")) ... will not ask confirmation when the flag overwrite_files is set.
To understand the following it is also important to note that x++ is postincrementation what means that in if( x++) x has the old value but just in the next line (or even same line but after if() was tested) x is incremented.
(i)
if(x++ && y++) // x=2,y=0;
// 2 so y++ is evaluated
cout<<x<<y; // skipped, but now x=3,y=1;
Output:
(ii)
if(y++ || x++) // x=2,y=0;
//0 so x++ is evaluated
cout<<x<<" "<<y; // x=3,y=1;
Output: 3 1
(iii)
if(x++||y++) // x=2,y=0;
//2 so y++ is not evaluated
cout<<x<<" "<<y; // x= 3,y=0;
"IF" argument evaluation order?
In C++ (and a few other languages) && and || are your logical operators in conditions. && is the logical AND operator and || is the logical OR operator.
When using these in a condition, the result of the condition is dependent on what is on either side of these operators and is read as if you were just saying the words.
Example:
if(thisNum > 0 && thisNum < 10) is read as "if thisNum is greater-than zero AND less-than 10, the condition will be true." Therefore, any number between 0 and 10 will make the condition true.
if(thisNum > 0 || thisNum < 10) is read as "if thisNum is greater-than zero OR less-than 10, the condition will be true." Therefore, ANY number at all will make this statement true because only one part of this statement has to be true to evaluate to TRUE.
A more detailed explanation on how these work is this:
OR (||) - If EITHER or BOTH sides of the operator is true, the result will be true.
AND (&&) - If BOTH and ONLY BOTH sides of the operator are true, the result will be true. Otherwise, it will be false.
There are many more explanations, including truth tables around the internet if you do a Google search to assist in understanding these.
As for your examples.
if(x++ && y++)
cout<<x<<y;
You are doing an if statement that is comparing the the values of x and y. The important thing to remember is that you are NOT comparing the values together. In C++, and non-zero value will evaluate to TRUE while a zero value will result in FALSE. So, here you are checking to see if x AND y are TRUE and then increasing their values by one AFTER the comparison. Since x = 2 and y = 0, we have one TRUE value and one FALSE value and since we have a && (AND) operator between them we know the result of the condition is FALSE (since both aren't TRUE) and the output is skipped.
if(y++ || x++)
cout<<x<<" "<<y;
In this example, we are doing the same thing EXCEPT we are doing a logical OR operation instead of AND (since we have || and not &&). This means, as I said above, that only one part of the condition has to be TRUE to result in TRUE. Since our values are still x = 2 and y = 0, we have one TRUE value and one FALSE value. Since part is TRUE, the whole condition is TRUE and the output occurs.
The reason the result is 3 1 and not 2 0 is because of the ++ operators after the variables. When the ++ operators are after the variable, it will add one AFTER the rest of the line has occurred and done the actions it needs. So it does evaluates the condition THEN increases the values by one.
if(x++||y++)
cout<<x<<" "<<y;
This example is EXACTLY the same, the only difference is that the values have been swapped. And since it is an OR (||) operation, only one part has to be TRUE. And as before, we have one TRUE value (since x is non-zero) and one FALSE value (since y is zero). Therefore, we have a TRUE result, meaning the output is NOT skipped and we get the answer 3 1 again (since the ++ operators came AFTER the variables).
Now, speaking of the ++ operator. What if in the first example it had been:
if(++x && ++y)
cout<<x<<y;
We would get a DIFFERENT result in this situation. Since the ++ operator comes BEFORE the variables, the first thing that happens is that the values are increased by one AND THEN the condition is evaluated. Since our new values would be x = 3 (TRUE) and y = 1 (also TRUE), we can conclude that we would get the same result as the other two examples since BOTH values are TRUE (which, since we have an AND (&&) operator, BOTH variables have to be TRUE to result in TRUE).
Hope this helps.
EDIT:
One of the other answers made an excellent point about the second and third examples. Result wise, there is no difference. HOWEVER, in terms of how it is evaluated there is a difference.
C++ automatically does something called "short-circuit evaluation". This means, it will skip any evaluations if it knows the result is already going to be TRUE or FALSE. This means that with an OR operation, if the first part is TRUE it will just skip the second part since it already knows the result HAS TO BE TRUE. (Remember, with OR only one part of the comparison has to be TRUE.) So this means that IF the first part is FALSE then the program HAS TO evaluate the second part too, since it determines whether the result will be TRUE or FALSE.
With an AND operation, it will do the opposite. If the first part is FALSE then the program knows the result has to be FALSE and will skip the rest. However, if the first part is TRUE then the program HAS TO evaluate the rest to determine if the result is TRUE or FALSE.
In terms of your examples, this means the second one HAS TO evaluation both sides since the first part results in FALSE.
In the third example, the second part is skipped because the first part is TRUE, meaning the whole condition is TRUE.
For or(||) operator, if the expression of left side is true, it will ignore the expression of right side.
For and(&&) operator, if the expression of left side is false, it will ignore the expression of right side.
This is the answer of your question what makes the difference between (ii) and (iii).
In the output (ii), it is:
as the time where compiler is evaluating y, y is equal to 0 so the statement is false it s evaluating the other member x which is equal to 2 so the statement is true. And then it operates the increment operator.
In the output (iii), it is:
as the time where compiler is evaluating x, x is equal to 2 so the statement is true as the operator of the condition is || it won't evaluate the other expression so the y++ is ignored. Only x will be incremented.

What is this syntax in while loop condition?

while ( (i=t-i%10 ? i/10 : !printf("%d\n",j)) || (i=++j<0?-j:j)<101 );
I came across this on codegolf
Please explain the usage of ? and : and why is there no statement following the while loop? As in why is there a ; after the parenthesis.
There is a boolean operation going on inside the parentheses of the while loop:
while (boolean);
Since the ternary operator is a boolean operator, it's perfectly legal.
So what's this doing? Looks like modular arithmetic, printing going on over a range up to 101.
I'll agree that it's cryptic and obscure. It looks more like a code obfuscation runner up. But it appears to be compilable and runnable. Did you try it? What did it do?
The ?: is a ternary operator.
An expression of form <A> ? <B> : <C> evaluates to:
If <A> is true, then it evaluates to <B>
If <A> is false, then it evaluates to <C>
The ; after the while loop indicates an empty instruction. It is equivalent to writing
while (<condition>) {}
The code you posted seems like being obfuscated.
Please explain the usage of ? and :
That's the conditional operator. a ? b : c evaluates a and converts it to a boolean value. Then it evaluates b if its true, or c if its false, and the overall value of the expression is the result of evaluating b or c.
So the first sub-expression:
assigns t-i%10 to i. The result of that expression is the new value of i.
if i is not zero, the result of the expression is i/10
otherwise, print j, and the result of the expression is zero (since printf returns a non-zero count of characters printed, which ! converts to zero).
Then the second sub-expression, after ||, is only evaluated if the result of the first expression was zero. I'll leave you to figure out what that does.
why is there no statement following the while loop?
There's an empty statement, ;, so the loop body does nothing. All the action happens in the side effects of the conditional expression. This is a common technique when the purpose of the code is to baffle the reader; but please don't do this sort of thing when writing code that anyone you care about might need to maintain.
This is the Conditional Operator (also called ternary operator).
It is a one-line syntax to do the same as if (?) condition doA else (:) doB;
In your example:
(i=t-i%10 ? i/10 : !printf("%d\n",j)
Is equivalent to
if (i=t-i%10)
i/10;
else
!printf("%d\n",j);
?: is the short hand notation for if then else
(i=t-i%10 ? i/10 : !printf("%d\n",j)<br>
equals to
if( i= t-i%10 )
then { i/10 }
else { !printf("%d\n",j) }
Your while loop will run when the statement before the || is true OR the statement after the || is true.
notice that your code does not make any sense.
while ( (i=t-i%10 ? i/10 : !printf("%d\n",j)) || (i=++j<0?-j:j)<101 );
in the most human-readable i can do it for u, it's equivalent to:
while (i < 101)
{
i = (t - i) % 10;
if (i > 0)
{
i = i / 10;
}
else
{
printf("%d\n",j);
}
i = ++j;
if (i < 0)
{
i = i - j;
}
else
{
i = j;
}
}
Greetings.
I am the proud perpetrator of that code. Here goes the full version:
main()
{
int t=getchar()-48,i=100,j=-i;
while ((i=t-i%10?i/10:!printf("%d\n",j)) || (i=++j<0?-j:j)<101 );
}
It is my submission to a programming challenge or "code golf" where you are asked to create the tinniest program that would accept a digit as a parameter and print all the numbers in the range -100 to 100 that include the given digit. Using strings or regular expressions is forbidden.
Here's the link to the challenge.
The point is that it is doing all the work into a single statement that evaluates to a boolean. In fact, this is the result of merging two different while loops into a single one. It is equivalent to the following code:
main()
{
int i,t=getchar()-'0',j=-100;
do
{
i = j<0? -j : j;
do
{
if (t == i%10)
{
printf("%d\n",j);
break;
}
}
while(i/=10);
}
while (j++<100);
}
Now lets dissect that loop a little.
First, the initialisation.
int t=getchar()-48,i=100,j=-i;
A character will be read from the standard input. You are supposed to type a number between 0 and 9. 48 is the value for the zero character ('0'), so t will end up holding an integer between 0 and 9.
i and j will be 100 and -100. j will be run from -100 to 100 (inclusive) and i will always hold the absolute value of j.
Now the loop:
while ((i=t-i%10?i/10:!printf("%d\n",j)) || (i=++j<0?-j:j)<101 );
Let's read it as
while ( A || B ) /* do nothing */ ;
with A equals to (i=t-i%10?i/10:!printf("%d\n",j)) and B equals to (i=++j<0?-j:j)<101
The point is that A is evaluated as a boolean. If true, B won't be evaluated at all and the loop will execute again. If false, B will be evaluated and in turn, if B is true we'll repeat again and once B is false, the loop will be exited.
So A is the inner loop and B the outer loop. Let's dissect them
(i=t-i%10?i/10:!printf("%d\n",j))
It's a ternary operator in the form i = CONDITION? X : Y; It means that first CONDITION will be evaluated. If true, i will be set to the value of X; otherwise i will be set to Y.
Here CONDITION (t-i%10) can be read as t - (i%10). This will evaluate to true if i modulo 10 is different than t, and false if i%10 and t are the same value.
If different, it's equivalent to i = i / 10;
If same, the operation will be i = !printf("%d\n",j)
If you think about it hard enough, you'll see that it's just a loop that checks if any of the decimal digits in the integer in i is equal to t.
The loop will keep going until exhausting all digits of i (i/10 will be zero) or the printf statement is run. Printf returns the number of digits printed, which should always be more than zero, so !printf(...) shall always evaluate to false, also terminating the loop.
Now for the B part (outer loop), it will just increment j until it reaches 101, and set i to the absolute value of j in the way.
Hope I made any sense.
Yes, I found this thread by searching for my code in google because I couldn't find the challenge post.

Bizarre condition syntax

I came across the following for loop with a very unusual condition
int main( int argc, const char* argv[] ) {
for ( int i = 0 ; i < ( 10, 20 ) ; i++ ) {
cout << i << endl;
}
}
This source code compiled successfully. It executed the loop with i with values from 0 to 19 (the 10 in the expression (10, 20) seems to have no effect on the number of iterations).
My question:
What is this condition syntax? Why doesn't it cause a compile error?
EDIT:
The bigger picture: this questions started with a bug, the original condition was supposed to be i < std::min( <expr A>, <expr B> ) and for some reason I omitted the std::min.
So, I was wondering why the code compiled in the first place. Now I see the bug is a legit (albeit useless) syntax.
Thanks!
It is the comma operator. It evaluates both sides of the expression, and returns the right one.
So, expression (10, 20) does nothing, but returns '20'.
See also
Uses of C comma operator.
http://en.wikipedia.org/wiki/Comma_operator
(10, 20) means evaluate the integer 10, then evaluate 20, then return 20 (the rightmost). So it just means 20.
The comma operator is often useful in for loops, as it allows things such as x = 0, y = 1 (i.e. two assignments in one expression), but here it's useless.
, operator in c++ work as a binary operator which checks first value, discard it and return the next value. In short.
for(int i=0;i<(10,20);i++) will be equal to for(int i=0;i<20;i++)