0

while loop

int x = 0; int&y = x; y=5; while (x <=5) { cout << y++; x++; } cout << x; // outputs 57 What's the purpose of the "int&y = x" ? My thought process: run 1 of loop: y++ prints 5 and x is incremented to 1 run 2 of loop: y++ prints 6 and x is incremented to 2 run 3 of loop: y++ prints 7 and x is incremented to 3 run 4 of loop: y++ prints 8 and x is incremented to 4 run 5 of loop: y++ prints 9 and x is incremented to 5 run 6 of loop: y++ prints 10 and x is incremented to 6 While loop's condition is unmet and thus terminates, and x of value 6 is printed. Why isn't the output 56789106? What information am I missing about line 2 of the code? I basically ignored int&y = x

24th Jul 2020, 9:39 AM
Solus
Solus - avatar
2 ответов
+ 2
The line int& y = x; is crucial because it declares a reference. You can read up on them in detail e.g. here https://www.geeksforgeeks.org/references-in-c/amp/ but to make it short, a reference is like an alias for a variable, so both the original variable and the reference refer to the same value. It's quite similar to a pointer without all of the asterisk syntax, although there are some conceptual differences: https://stackoverflow.com/questions/57483/what-are-the-differences-between-a-pointer-variable-and-a-reference-variable-in This is important because it means the next line y = 5; also leads to 'x' being 5. Now both 'y' and 'x' equal 5, so this is printed and 'y' incremented, so both equal 6 after the first print statement. Afterwards, 'x' is incremented, meaning they equal 7 now. As a consequence, the loop condition fails, and the value of 'x' is printed, thus the final output comes as 57. Basically, just try to think of 'x' and 'y' as two names for the same variable.
24th Jul 2020, 10:11 AM
Shadow
Shadow - avatar
0
A variable can be declared as reference by putting ‘&’ in the declaration. When a variable is declared as reference, it becomes an alternative name (aka alias) for an existing variable. In this case, the y is made to be the reference for x because there is a '&' before it (as observed in int&y = x ). When the reference is assigned a (most likely different) value, the existing variable is also assigned to THAT same value. In this case, assigning y=5 induces the value 5 to be assigned to x. Now x=5. Moving on to the while loop. The cout << y++ prints 5 and increments y. This means that the reference is re-assigned a different value of 6. By the same token, the existing variable, x, must also immediately be assigned 6 (before line x++ executes). Now x=6. THEN x becomes incremented by x++. Now x=7. Following this, the while loop terminates. The cout << x prints 7.
25th Jul 2020, 1:40 AM
Solus
Solus - avatar