Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does int * & has any real sense?

Tags:

c++

function

I'm looking few exercise from university about C++ and I found out this exercise:

#include <iostream>
using namespace std;
int& f(int*&);
int& f(int*& x) {
    *x = 5;
    return *x;
}
int main() { 
    int y = 1, x; 
    int* z = &y; 
    x= f(z);
    cout << y << " " << x <<endl; 
}

I was wondering: does <any type>*& has any real sense? Isn't f(int*& x) the same as f(int x)? Aren't you passing the pointer to the L-value of the variable?

like image 529
Shoe Avatar asked Nov 19 '25 02:11

Shoe


1 Answers

f(int*& x) is not the same as f(int x). In the first case x is a reference to an integer pointer whereas in the second case x is just an integer.

Lets start from the basics:

When you write f(int &x) means that x is a reference to an integer and you can change the value of x in the function and the change will be reflected in the calling function.

Similarly, when you write f(int*& x), it means that x is reference to an integer pointer and when you change the address that x points to, the change will also be reflected in the calling function.

like image 113
Pulkit Goyal Avatar answered Nov 20 '25 16:11

Pulkit Goyal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!