Output in c++ and why? - c++

code
#include<iostream>
using namespace std;
int &fun()
{
int x = 10;
return x;
}
int main()
{
fun() = 30;
cout << fun();
return 0;
}
output wil be 10 , tell me how and when int x = 10 is changed to static int x = 10 output will be 30 .Explain both of the cases .

This is undefined behavior. You are returning a reference to a local variable whose lifetime has ended at the end of the function.
It's quite amusing what g++ does with this code:
At -O0, it prints 10.
At -O1, it prints 30.
At -O2 and -O3, it prints 0.
If you declare x as static, then it has static storage duration, which means that its lifetime doesn't end when the function returns, which means that it is legal to return a reference to it. All calls to foo will return a reference to the same int.

Related

My division function returns a zero. Should I declare x differently in main?

#include <iostream>
using namespace std;
int division(int c, int d);
int x = 2;
int y = 2;
int division(int c, int d)
{
return (c/d);
}
int main()
{
cout << "Hello World!\n";
int x = division(x,y);
cout << x;
return 0;
}
I expected the code to show 1 after Hello World!, but it prints 0.
I removed int from in front of x (in main()) and ran it again and it returned 1.
But I also passed x,x to the division function with the int in front of x (in main()) and it returned 1.
So I am not sure how the assignment statement is working.
This expression:
int x = division(x,y);
is equivalent to writing this:
// 'x' was defined globally somewhere here before
int x;
x = division(x, y);
This shadows the previous x variable defined globally and defines a local variable x which again is uninitialized so after passing it in the division() function, your code has Undefined Behavior. (When that happens, the output can be anything, it can be 0, it can even be 1 or something else entirely.)
What you want to do is to remove the declaration and turn it into an assignment instead:
x = division(x,y);
Then the above works properly and gives 1.
You should compile your code at least with -Wall flag.
You would then see a helpful warning message:
foo.cpp: In function ‘int main()’:
foo.cpp:17:21: warning: ‘x’ is used uninitialized [-Wuninitialized]
17 | int x = division(x,y);
| ~~~~~~~~^~~~~
It means that to the division() isn't passed global x, but the local one from main().
It's undefinied behaviour, no different than int z = division(z,y);
After removing int from before x in main() you no longer declare local variable, thus there is only one x in your program (the global one) and from initialization the line turns into plain assignment.

what does &fun() refer to in the program?

This is an example problem to demonstrate the use of references in c++. i'm a beginner and this is my first time learning about references. i don't understand why we use &fun(). what does it mean?
#include<iostream>
using namespace std;
int &fun(){
static int x = 10;
return x;
}
int main(){
int &y=fun();
y = 20;
cout<<fun();
}
output : 20
Equivalent syntax is int& fun().
So this function returns a reference to 'x' (that is static), so later in main you can modify it (y = 20 does change the x inside the function).
So another invocation returns 20, as the x had been changed.
int & means fun() is returning a reference to an int. In main(), that reference is assigned to y, and the value of y is modified to 20, also changing the value of x to 20.

Can you tell me how the code given reachs to that output?

the output of the code is 30.But I am not sure how it is getting to it.
#include <iostream>
int &fun()
{
static int x = 10;
return x;
}
int main()
{
fun() = 30;
std::cout << fun();
return 0;
}
I am expecting that the output will be 10 but its showing 30. how?
Your fun gives a location of an int (since it returns a reference). That location is the static variable x which is initialized (once, conceptually before the program runs) to 10.
Then fun() = 30; is assigning that location. So x gets assigned to 30.
At last cout << fun() displays the content of that location.
If x was some automatic variable your code would have undefined behavior.
PS. A crude way of thinking about & unary reference like int &r = x; is that it sort-of "transforms" your code as: introduce a phantom pointer int *p = &x; (where p is some fresh variable not appearing elsewhere) and replace r with *p, so &r with p, everywhere in the scope of that r.

References - Why do the following two programs produce different output?

I recently read about references in C++. I am aware of basic properties of references but I am still not able to figure out why following two programs produce different output.
#include<iostream>
using namespace std;
int &fun()
{
static int x = 10;
return x;
}
int main()
{
fun() = 30;
cout << fun();
return 0;
}
This program prints 30 as output. As per my understanding, the function fun() returns a reference to memory location occupied by x which is then assigned a value of 30 and in the second call of fun() the assignment statement is ignored.
Now consider this program:
#include<iostream>
using namespace std;
int &fun()
{
int x = 10;
return x;
}
int main()
{
fun() = 30;
cout << fun();
return 0;
}
This program produces the output as 10. Is it because, after the first call, x is assigned 30, and after second call it is again overwritten to 10 because it is a local variable? Am I wrong anywhere? Please explain.
In the first case, fun() returns a reference to the same variable no matter how many times you call it.
In the second case, fun() returns a dangling reference to a different variable on every call. The reference is not valid after the function returns.
When you use
fun() = 30;
in the second case, you are setting the value of a variable that is not valid any longer. In theory, that is undefined behavior.
When you call fun() the second time in the second case, the variable x is set to 10. That is independent of the first call to the same function.
Just adding to what has been said. The reason behind the first case's behavior is because it is a static variable, which has a static duration. Static duration means that the object or variable is allocated when the program starts and is deallocated when the program ends.
This means that once x in the first case has been initialized the first time with 10, the next function call will ignore static int x = 10; because x cannot be instantiated again, as it has already been allocated, and will simply proceed to return x;, which will be the same x that was assigned 30 in main.
Basically, your understanding is right, except for in 2nd case, you're processing a dangled reference of the local variable has been invalid, which is undefined behaviour, means anything is possible. What you said is just one of the possibility, it also could result in others, such as getting a random number, program crash, etc.

How could an integer variable store a reference to integer?

I was searching for explanations over reference variables in c++ and I found this:
#include<iostream>
int a=10; //global 'a' so that fun doesn't return a reference of its local variable
int & fun();
int main()
{
int p = fun(); //line to be noted
std::cout << p;
return 0;
}
int & fun()
{
return a;
}
This worked and so does this:
#include<iostream>
int a=10; //global 'a' so that fun doesn't return a reference of its local variable
int & fun();
int main()
{
int &p = fun(); //line to be noted
std::cout << p;
return 0;
}
int & fun()
{
return a;
}
My question is how could an integer variable store the value of reference as is being done in first code snippet [line number 6]. Isn't the correct syntax as depicted in code snippet 2 [at line 6], i.e. we should define a reference variable (int &p) to carry the reference and not a regular integral variable?
Shouldn't the compiler give an error or at least a warning? I am using GCC 4.7.1 64-bit.
Okay got it ... #chris : you were right..When I did this:
int p = fun();
p++;
std::cout << p << endl << a;
It showed the results to be 11 and 10. Hence only a's value is copied into p and p doesn't became the alias of a.
But when I tried the same with second code, it showed values of both a and p to be 11. Hence p became the alias of a.
No, it is fine either way.
The return value reference is not even necessary in this special case because you are not trying to modify the return value "on the fly" or the 'a' later, like when you use arithmetic operator overloads for that purpose, for instance