I recently came across this c++ example from cppinstitute and I have no idea how the conversion from int* to int& works.
the output of f2 is a pointer, however, f3 takes an int& how is the pointer turned into a variable so that f3 can take it by reference?
to be more precise, how can we write it in 3 lines?
the main code :
#include <iostream>
using namespace std;
int f1(int *a) {
return *a + 1;
}
int *f2(int *a) {
return a + 1;
}
int *f3(int &a) {
return &a + 1;
}
int main() {
int t[] = {0, 1, 2, 3};
cout << f1(f3(*f2(t)));
return 0;
}
how to assign the return values and pass them like this ?
int * a = f2(t);
int * b = f3(a); /*some kind of conversion is hapenning here*/
int c = f1(b);
cout << c;
the above code won't compile and the compiler complains that a
is an int*
not an int
. dereferencing a
and passing it like f3(*a)
will compile however won't produce the same result as the original code.
edit I made a mistake f3(*a) will compile and produce the same result. thanks eerorika