function usage

I need help. I dont understand something and I realized that this is very important.

#include <iostream>

using namespace std;

void f(int x)
{
x = 2;
}

int main()
{
int y = 0;
f(y);
cout << y;
}

why is the output 0 ?
Im really confused because I had a problem and I just realizez this is the issue.
And how should I switch this program to work? Please explain me because this is very important!
It makes a local copy of x, assigns that 2, and exits. Y is unchanged.

to fix it:

void f(int &x) //this makes a reference to what was passed in, and ensures that y is updated by the function call. The reference is different from the local copy, the reference is really Y, while the copy is just moving the value of y (0) into x then over-writing that and finally destroying it without doing anything.

another option is this type of function:
int f (int x)
...
return x;
-------------------------
y = f(y); //y is assigned the result of the function, which is the return statement.


I prefer the int f style personally. I usually find reference modifications to be clunky, often resulting in a strange function header where the user has to pass in the storage variable for the result which feels off to me. There are times when one or the other makes more sense, and sometimes it is just style. here, it is just style.
Last edited on
yes i know the second option and i know its easier, but my progra was using a fill algorithm which is void and i used some variables in it, thanks a lot ,but can you please take your time to explain me the pointers, I dont know them at all, thanks so much
i dont know how to declare a variable as a pointer as example
you need a return type other than void if u want your function to pass back a value, in this case int
Last edited on
you don't need any pointers.

void foo(int &x) //this is what you need to know and do. the &.
{
++x;
}

int y = 0;
foo(y);
cout <<y << endl; //y is 1
foo(y);
cout <<y << endl; //y is 2
...
etc

I can show you some pointers, but you don't need any here.
under the hood, at the machine language level, references are more or less pointers and become such in the assembly languages for most use-cases. But you don't need to know that to use them :)

int *x; //a pointer to an integer.
x = &y; //x now points to y.
x = new int[10]; //x is now an array of 10 integers

you could have done this:

void foo(int *x)
{
x[0]++;
}

..
foo(&y); //take the address of y (a pointer) and put it into the pointer parameter.
this is overly complicated and of no value to do it this way; its harder to read, harder to write, and can lead to more places where you might have errors. This is not helpful to do right now.




Last edited on
thanks
Topic archived. No new replies allowed.