Jump to content

So I am doing this assignment and I am supposed to predict the output in the console and I came across this program that confuses me.

 

My prediction for the output of this program goes like this: 

 

main: 10

val: 10

main: 10

ref: 10

main: 5

constref: 5

ref: 5

main: 5

 

 

The actual output goes like this: 

 

main  : 10

val : 10

main  : 10
ref : 10
main  : 5
constref : 5
main  : 5
 
 
The code for this program is:

#include <iostream>using namespace std;void val(int x);void ref(int &x);void constRef(const int & x);int main(void){	int m = 10;	cout << "main  : " << m << endl;	val(m);	cout << "main  : " << m << endl;	ref(m);	cout << "main  : " << m << endl;	constRef(m);	cout << "main  : " << m << endl;	return 0;}void val(int x){	cout << "val : " << x << endl;	x = 5;}void ref(int &x){	cout << "ref : " << x << endl;	x = 5;}void constRef(const int &x){	cout << "constref : " << x << endl;	//x = 5;	ref(x) ;}
 
 

 

Why is there no second ref: 5 output? 

 
Link to comment
https://linustechtips.com/topic/526228-pass-by-reference-c-question/
Share on other sites

Link to post
Share on other sites

There is a function in std that is called ref. Your code is using that function instead of the one you expect (for the second call to ref.) If that function didn't exist you would get a compile error for trying to pass a const variable to a non const parameter. 

 

So the lesson here is, don't do "using namespace std;" or any other namespace.

 

edit: words

1474412270.2748842

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×