(C++) Infinite zeros with the addition operator in a small loop - c++

i have a little problem with this small piece of code;
If i use the ++ operation (x++) it works fine, but if i write "x + 1" it breaks and causes an infinite loop of zeros.
The code:
int x = 0;
while (x <= 20)
{
std::cout << x << std::endl;
x + 1;
}
Any help would be appreciated!

If you want to set a value of a variable you must* use an =.
This : x + 1 is NOT the same as x = x + 1 or x += 1 or x++.
When you add that x plus to your code you are never changing the value of x.
x + 1 simply returns a temporary value of the result. Where as the other three listed about will change the value of x instead of creating a temporary value.

You need to know the differences between different statements related to increment as below.
x++ means x = x + 1; which means copy the value of x into temporary
register, increment the value by 1 and write that register value back
into x.
x + 1 means, copy the value of x into temporary register, increment
the value by 1. You are not assigning the value back to x. So x value
won't be changed.
So in your while loop, x value is not being changed which is reason for infinite loop.

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).

Understanding the operator "less" or "greater" in assigning value with C++

I used greater than and less than signs and it gives ouput! How it is working ?
int x = 2;
x >= 3;
cout << x; // output is 2
And also the output is different like this
int x = 2;
x = x > 3;
cout << x; // output is zero !! HOW ??
The expression
x >= 3
is a pure comparison. It tests, whether the value of variable x is greater than, or equals 3. The result is 0 or 1 – for x equal 2 it is zero, false.
Terminating the expression with a semicolon creates a statement. That statement performs a comparison and ...nothing else. The result of comparison is discarded, and the variable x remains unchanged. Hence the observed resulting value 2.
In x = x > 3; the subexpression x > 3 is a comparison. Its result is 1 if the comparison succeedes, 0 otherwise.
Since you initialized x to 2, the result of the comparison is false, i.e. zero.
As a result
x = x > 3;
equivalent to
x = (x > 3);
resolves to
x = 0;
hence the output you observed.
If you use
int x = 2;
x >= 3;
cout << x;
the output is 2 because the result of the x >= 3 operation is discarded (not used) and x remains by the same value as it were initialized. x was not assigned by any value after its initialization.
If you use
int x = 2;
x = x > 3;
cout << x; `
x is checked whether it is greater than 3 or not with x > 3. If it is, the value of the expression x > 3 turns 1, if not it turns 0. Comparison operations are boolean expressions.
This boolean value is assigned back to x after the evaluation of x > 3.
Since x is not greater than 3, the expression x > 3 gains the value 0 and this value is assigned back to x and finally what is printed.

C++ while statement not equal checks

I started coding in C++ (VS 2015).
Wrote a little program which using a while statement.
#include <iostream>
using namespace std;
int main() {
int x = 1;
int y = 2;
int z = 0;
while (x != y || z != y) {
cout << "x: " << x << "\n" << "z: " << z << "\n";
x++;
z++;
}
cin.get();
}
If i get this correctly it should work in that way (but since its going to an infinite loop i guess my logic is not as correct as i think).
So in my mind the while statement should work in that way.
While X not equal to y OR z not equal to y.
add +1 to X and +1 to Z.
Do this until the statment became true (or atleast the left side of the expression).
There's no iteration where both of your conditions become evaluated to false at a certain point, hence the loop doesn't stop.
You can easily investigate that behavior by stepping through your code using a debugger, and watch how the variable values change.
Loop iterations
x=1, y=2, z=0, condition: true
x=2, y=2, z=1, condition: true
x=3, y=2, z=2, condition: true
. . . and so on
The condition never evaluates to false, and leads to infinite loop. Consider changing to and operator to make the loop finite, or maybe change some values.
while (x != y && z != y) {
Output
x: 1
z: 0
The 1st expression of while condition is becoming false after first iteration.
the 2nd expression is becoming false after a couple of iteration, but after first execution the first expression is becoming true again, and your program runs forever because infinite loop.
the loop will keep iterates because whenever the x and y value is increased, it will never become 0, which is equals to the value that is assigned to y. (simple logic)
Change this statement-> while(x!=y||z!=y) into this-> while(x!=y && z!=y)
you should get the output:
x:1
z:0

Magic in C++ with this expression x = y - x + (y = x) [duplicate]

This question already has answers here:
Why are these constructs using pre and post-increment undefined behavior?
(14 answers)
Closed 8 years ago.
In Python, you can easily exchange the values of 2 variables with an expression like this:
x, y = y, x
In C++, on the other hand, if you want to exchange the values of 2 variables, you usually use a temporary variable to store the value of one of your variables, something like this:
int var1 = 100;
int var2 = 200;
int temp = var1;
var1 = var2;
var2 = temp;
This is easy, but you have to write a lot of code.
A professor that I have been following for his lectures on C++ has discovered a new compact way of exchange the values of 2 variables in a magic way:
int x = 200;
int y = 100;
x = y - x + (y = x);
It seems incredible, but it works both with the compiler he's using and mine Apple LLVM version 6.0 (clang-600.0.56).
It seems that the way that expression is interpreted is the following:
(y = x) // returns the value of x
-x + x = 0
x = y + 0
x = y
y = x // finally, y receives the initial value of x
If I try to exchange the values of some variables in a loop, it seems also to work:
for (int i = -10; i <= 10; i++) {
for (int j = 10; j >= -10; j--) {
int x = i, y = j;
x = y - x + (y = x);
std::cout << "x = " << x << "\ny = " << y << '\n';
}
}
We have seen that the exchange is done, but my compiler gives me this warning:
main.cpp:28:22: warning: unsequenced modification and access to 'y'
[-Wunsequenced]
If there's a warning, I suppose this is not a new standard way of exchanging the values of 2 variables, but was just an ingenious workaround of this professor.
Why this method is not standardised in C++, and why exactly does it work?
This is undefined behavior, and it's not guaranteed to work. The order of evaluation of the parameters in an expression is not specified. So it's allowed to access the value of y for the subtraction before or after it performs the y = x assignment.
The reason it's specified like this is to allow flexibility for optimizations.
It "works" because you were unlucky.
Yes, I said unlucky. The code has undefined behavior; the fact that it appears to "work" means that your compiler has let you get away with code that could fail next time you run it.
x = y - x + (y = x);
The object y is accessed twice, once to read its value and once to assign a value to it. The language does not define the order in which those accesses occur -- or that the occur in any order at all. As the warning message says, they're "unsequenced". The possible behaviors are not limited to the two possible orders; the behavior is entirely undefined.
Furthermore, the addition and/or subtraction could overflow, which is another potential source of undefined behavior.
This, `x = y - x + (y = x);, is undefined behavior in C - one undefined behavior listed by the C99 spec is:
Between two sequence points, an object is modified more than once, or
is modified and the prior value is read other than to determine the
value to be stored
The only sequence points in this expression are the beginning of the expression and the end of the complete expression.

need understanding of while loop condition (see comment)

while (x >= 1000)
{
cout << "M";
x -= 1000;
}
Can someone explain to me how this while loop works? I understand the condition is for x is greater or equal to 1000, it will print out 'M'.
The part after that is what I actually don't understand, is it saying that it will keep subtracting a thousand from X and keep printing until the condition is false?
Yes, that is exactly what it will do.
This translates roughly into:
While x is greater than or equal to 1000, do what is in the code block (over and over until the condition fails)
The code block then prints M and sets x equal to itself minus 1000. (x -= 1000 is the same as x = x - 1000
Hypothetical:
x = 3000
x is greater than 1000
print M
x is set to 2000
loop resets and checks x...passes test
print M
x is set to 1000
loop resets and checks x...passes test because of = portion
print M
x is set to 0
loop resets and checks x...fails
moves to the code after the while code block
while (x >= 1000) //x is greater than or equal to 1000
{ //executes loop if condition true, else the statement after the loop block
cout << "M"; // print M
x -= 1000; // x = x-1000
} //goes back to condition checking
You are right!
x-=1000;
is actually
x=x-1000;
Yes.
it saying that it will keep subtracting a thousand from X and keep printing until the condition is false
The program appears to be an inefficient way of writing
x %= 1000;
which is x = x%1000, where % is the modulus operator.
Your code reaches the same result by subsequent substraction, and stops when x<1000.