C++ Why am I getting this output. (Greenhorn here) - c++

So in the following bit of code, I've been trying to figure out as to why the output of the code comes out to be...
X = 2 and Y = 2
when I originally thought it would be x = 1 and y = 1. I'm still a lil mind boggled with C++ coming into the semester and a little explanation with someone with more knowledge than me on this can hopefully mesh this concept into my head.
int main()
{
int x = 0;
int& y = x;
y++;
x++;
std::cout << "x = " << x << " y = " << y << std::endl;
}

x and y are not different than each other. Reference means the other name of x is y. So when you call y it calls x which means if you increase y it increases x. Then you increase x again and x becomes 2. And because y represents x, when you call y it calls x and you see 2 again.

key point is what the reference sign meant:
int& y = x;
It represent that you are assigning an alias to 'x', so 'y' is actually sharing the same memory address as 'x' do (physically).
doing
y++;
will change the value inside that memory address, which is shared by both 'x' && 'y'. Same as the operation
x++;
As a result, you did 2 increment on the same memory address with intial value of '0', which the value becomes '2'.
same idea, since both 'x' and 'y' are pointing to that exact same memory address, printing 'x' and 'y' will give you the same value.

Related

Why is int x{ y = 5 } possible?

int main() {
int y;
int x{ y = 5 };
//x is 5
}
How is this possible, since y = 5 is not a calculable expression?
Also, why doesn't the compiler or IDE complain about main() not returning an int?
How is this possible, since y = 5 is not a calculable expression?
It is an assignment, and assignments yield values, i.e. the "cv-unqualified type of the left operand", see [expr.ass/3]. Hence y = 5 results in y, which is 5, which is used to initialize x.
With respect to your second question, see cppreference on main (or [basic.start.main/5]):
The body of the main function does not need to contain the return statement: if control reaches the end of main without encountering a return statement, the effect is that of executing return 0;.
Hence, compiler or IDE warning you about a missing return statement at the end of main would be plain wrong. Admittedly, the fact that you should always return objects from non-void functions execpt main is kind of... well, for historical reason I guess.
I will start from your last question
Also, why doesn't the compiler or IDE complain about main() not
returning an int?
According to the C++ Standard (6.6.1 main function)
5 A return statement in main has the effect of leaving the main
function (destroying any objects with automatic storage duration) and
calling std::exit with the return value as the argument. If control
flows off the end of the compound-statement of main, the effect is
equivalent to a return with operand 0 (see also 18.3).
And relative to this question
How is this possible, since y = 5 is not a calculable expression?
From the C++ Standard (8.18 Assignment and compound assignment operators)
1 The assignment operator (=) and the compound assignment operators
all group right-to-left. All require a modifiable lvalue as their left
operand and return an lvalue referring to the left operand.
Sp this declaration
int x{ y = 5 };
can be equivalently split into two statements
y = 5;
int x{ y };
Moreover in C++ you can even to make a reference to the variable y the following way
int &x{ y = 5 };
Here is a demonstrative program
#include <iostream>
int main()
{
int y;
int &x{ y = 5 };
std::cout << "y = " << y << '\n';
x = 10;
std::cout << "y = " << y << '\n';
}
Its output is
y = 5
y = 10
You may this declaration
int x{ y = 5 };
rewrite also like
int x = { y = 5 };
However take into account that there is a difference between these (looking similarly as the above declarations) two declarations.
auto x{ y = 5 };
and
auto x = { y = 5 };
In the first declaration the variable x has the type int.
In the second declaration the variable x has the type std::initializer_list<int>.
To make the difference more visible see how the values of the objects are outputted.
#include <iostream>
int main()
{
int y;
auto x1 { y = 5 };
std::cout << "x1 = " << x1 << '\n';
auto x2 = { y = 10 };
std::cout << "*x2.begin()= " << *x2.begin() << '\n';
std::cout << "y = " << y << '\n';
return 0;
}
The program output is
x1 = 5
*x2.begin()= 10
y = 10
The operator=() results in a value, which is the value assigned to the variable. Because of this, it is possible to chain assignments like this:
int x, y, z;
x = y = z = 1;
If you take a look at the documentation on cppreference, you'll see that operator=() return a reference to the object that was assigned. Therefore, a assignment can be used as an expression that returns the object that was assigned.
Then, it's just a normal assignment with braces.

Returning 0 after functions are called without "return(0);"

I'm having a small issue in trying to figure out why a zero is printed out at the end of my while loop.
#include <iostream>
using namespace std;
int x;
int CountDown(int x);
int CountUp(int x);
int main()
{
int toCountUp = CountUp(x);
cout << x << endl;
}
int CountUp(int x)
{
x = 0;
while(x <= 10)
{
cout << x << endl;
x++;
}
}
My best response would be that it is in the condition of the while loop. Or a return status from the function/main being fulfilled, but I don't have a return on there, and I know a function doesn't require a return statement but in this while loop I want there to be a integer returned, do I need to make the function void so there will be no return? But what about the parameter x that I need for the while loop?
code output:
0
1
2
3
4
5
6
7
8
9
10
0 < ---- this is the number I do not want.
Thinking about it, it has to be a value returned at the end of the function, any ideas?
This outputs the values 0 through 10:
int toCountUp = CountUp(x);
Then, this outputs 0:
cout << x << endl;
The method does not change the value that is passed to it, it uses its own local copy of that variable.
—It's mainly because you are printing cout << x << endl; twice. Once in the int CountUp(int x) function itself, but again in the main function.
—It could've printed any given value of x at this point, but since you're setting x=0 outside of the While{} loop in the int CountUp(int x) function, it's printing 0 at the end after the function call is executed.
*int CountUp(int x)
{
x = 0;
while(x <= 10)
{
cout << x << endl;
x++;
}
}*
—Is there a reason why you are setting x=0 within the function? since you're passing x as a parameter in the function call, and adding 1 to it in the While{} loop until it's x<= 10? Asking because you're not returning x back to the main() function.
—In case you wanted to use the end value of x to countdown using CountDown(x), you may like to reset x=0 in the main() function after calling the block—
*int CountUp(int x)
{
x = 0;
while(x <= 10)
{
cout << x << endl;
x++;
}
}*
At last 0 is printed in main() function because x is declared global.
If you want latest x after loop got over to be printed in main() then you should reference variable and don't declare it globally.
int CountUp(int &); /* function prototype*/
Since passed variable(actual argument) and reference variable having the same memory So modification will affects in calling function.
int CountUp(int &x) { /* catch with reference variable so that modification affects in calling function also */
x = 0;
while(x <= 10)
{
cout << x << endl;
x++;
}
}
First read Shadowing variables and What's the difference between passing by reference vs. passing by value?
The int x parameter of CountUp shadows the global variable int x so inside CountUp, the only x is the parameter.
int CountUp(int x)
int x defines x as passed by value, so it is a copy of the x used to call CountUp in main. This different x is counted up to 10 and then discarded.
the global int x has static storage duration and is default initialized to zero for you. Do not try this trick with a variable with Automatic duration because unless it has a constructor that does something useful, the contents are uninitialized and their value is undefined.
Sideshow issue:
A function that has a non-void return type MUST return a value on ALL paths. If it does not, you have Undefined Behaviour and the compiler can generate hopelessly invalid code that can get you even if the bad path is not taken. Don't smurf with Undefined Behaviour, as it might crash the program or do something hilariously wrong, but it might also look like it works until it suddenly doesn't at a really bad time.
Solutions:
void CountUp(int & x)
{
x = 0;
while(x <= 10)
{
cout << x << endl;
x++;
}
}
Passes x by reference allowing global x and the local x to be one and the same and returns nothing.
Usage would be
CountUp(x);
Not so useful in the asker's case because it doesn't leave a toCountUp.
int CountUp(int x)
{
x = 0;
while(x <= 10)
{
cout << x << endl;
x++;
}
return x;
}
Makes a copy if the provided x, operates on the copy, and then returns x. Usage would be
int toCountUp = CountUp(x);
And will set toCountUp to 10 higher than the global x.

[C++]Basic Array code that redefines y value. It's working but cannot explain why

I saw some codes on the web and trying to figure out how this works. I tried to leave comments on each lines but I cannot understand why y[0] changes to 5555. I'm guessing y[0] might change to numbers[0], but why?
x value is still 1. Well.. is this because y[0] = 1; has no int data type?
#include
using namespace std;
void m(int, int []);
/*this code explains a variable m that m consists of two parts, int and int array*/
int main()
{
int x = 1; /* x value is declared to 1*/
int y[10]; /*Array y[10] is declared but value is not given*/
y[0] = 1; /*Array y's first value is declared to 1 but data type is not given*/
m(x, y); /*This invokes m with x and y*/
cout << "x is " << x << endl;
cout << "y[0] is " << y[0] << endl;
return 0;
}
void m(int number, int numbers[]) /*variable names in m are given, number and numbers.*/
{
number = 1001; /*number has int 1001 value*/
numbers[0] = 5555; /*This overrides y to numbers[], so y[0] =1 changes to numbers[0] = 5555.*/
}
/*This program displays
* x is 1
* y[0] is 5005
* y[0] value has changed but x has not.
* */
I'm guessing y[0] might change to numbers[0], but why? x value is still 1.
Don't guess please. Your code works as commonly expected.
number = 1001; doesn't influence x in any way.
number is a local copy (as passed by value).
numbers decays to a pointer to the 1st element of the original array, thus it is changed outside the functions scope.
Well.. is this because y[0] = 1; has no int data type?
No, as explained above. y[0] actually is of type int.
int numbers[] is almost equivalent to int* numbers in this situation. You are not passing the vector as an immutable object but as a reference. So both numbers ( the local variable from the function ) and y ( the local variable from main ) will be pointing to the same memory address.

While Loop that increments a variable to a point

My goal for this program is to get input from the user for value 'y' and then multiply that value by 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, and then print the 10 results. Right now, when the user enters a value for 'y', the program just returns a list of zeros. Any idea what I'm doing wrong?
#include <iostream>
using namespace std;
int main(){
int x;
int y;
int z;
x = 0;
z = x * y;
cout << "enter y" << endl;
cin >> y;
while (x < 10) {
cout << z << endl;
x = x + 1;
}
}
The problem you have is that you don't actually calculate z inside the loop, so it will always be the value you calculated outside the loop. Statements and expressions can't be done retroactively.
But you have a worse problem than that, because you use y before you initialize it, which leads to undefined behavior.
You need to change the location of the y input to be before the calculation of z that should be inside the loop
The statement z = x * y should be inside your while loop for it to work.
What is happening now is that,each time it is printing the same value of z which is calculated initially as x(which is 0) and y(which is some garbage value as it has not been initialized) to give 0
The first problem occurring in your code is that try to assign z by multiplying x with y, but y is not assigned to a certain value => ERROR! That means you should get your user input before you assign z.
You may wonder why you get ten outputs of '0': Inside the loop you only print the value assigned to z to the console but z is already assigned before and not changed during the repetition.
#include <iostream>
using namespace std;
int main(){
int x;
int y;
int z;
x = 0;
z = x * y; // y is never assigned to a value
cout << "enter y" << endl;
cin >> y; // y got assigned here!
while (x < 10) {
cout << z << endl; // z stays the same in the loop
x = x + 1;
}
}

How do I emulate C++ postfix in bison?

I am trying to implement a simple compiler using flex & bison, and got stuck in the postfix notation.
(The compiler should behave like the C++ compiler)
Here is the problem:
Given the following code:
int x = 0;
int y = x++ || x++ ; //y=1 , x = 2 this is understandable
int z = x++ + x++ ; // z = 0 , x=2
the first line is fine because of the following grammar:
expression = expression || expression; // x=0
expression = 0 || expression // x= 1
expression = 0 || 1 //x=2
expression = 1 // x=2
y = 1
However, I don't understand why z=0.
When my bison grammar sees 'variable' ++ it first returns the variables value, and only then increments it by 1. I used to think thats how C++ works, but it won't work for the 'z' variable.
Any advice on how to solve this case?
int z = x++ + x++;
Although z may appear to be 0, it is not, it could in fact be any value and will depend entirely upon the compiler you are using. This is because the assignment of z has undefined behaviour.
The undefined behaviour comes from the value of x being changed more than once between sequence points. In C++, the || operator is a sequence point which is why the assignment of y is working as expected, however the + operator is not a sequence point.
There are of course various other sequence points in C++, the ; being a more prominent example.
I should also point out that the ++ operator returns the previous value of the variable, that is in this example
#include <iostream>
using namespace std;
int main() {
int x = 0;
int y = x++;
cout << y << endl;
return 0;
}
The value printed out for y is 0.
Saying the same thing another way. A C compiler is free to implement
int z = x++ + x++;
as either
z = x + x
incr x
incr x
or as
int r1 = x;
incr x
z = r1 + x
incr x
Your compiler appears to be using the first plan.