Just a query

I am learning c++ and i just came over passing by reference topic i created a code to understand the concept

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
  #include <iostream>
using namespace std;

int cubev(int x);
int cuber(int & x);

int main()
{
    int x=3;
    cout << "Enter a value\n";
    cout << "Cube of " << x << "= " << cubev(x) << endl;
    cout << cuber(x);
    cout << "\n = cube of " << x << endl;

}

int cubev(int x)
{
    x=x*x*x;
    


}

int cuber(int & x)
{
    x=x*x*x;
    


}


why the output is ''2293500 is cube root of 27'' when i don't use 'return x' in function cuber()??

Thanks in advance :)
Last edited on
in function cuber() x is passed by reference. That means if you change it value, value of passed function will be changed too.

I must note, that you do not return value from function declared as returning one. It leads to undefined behavior. That means anything can happen. It is absolutely legal for compiler go generate code formatting your hard drive and it will be conforming to standard.

Just to extend on MiiNiPaa's post, here is some corrected code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

#include <iostream>
using namespace std;

int cubev(int x);
void cuber(int & x);

int main()
{
	int x = 3;

	// pass by reference
	cuber(x);   
	cout << x << endl;  // show x, now its 27.

	// reset x
	x = 3;
	cout << cubev(x) << endl;

	return 0;
}

int cubev(int x)
{
	x = x*x*x;
	return x;
}

void cuber(int &x)
{
	x = x*x*x;
}
Thank you MiiNiPaa and Softrix
Topic archived. No new replies allowed.