Why does this work?

Just got to the point in Learning functions and did the end of chapter test and got it right, but then made a change in the function DoubleNumber changing the int from z to y expecting that the result would no longer be x2, but the function or program appears to x2 regardless of the DoubleNumber integer label?
Sorry for very basic question.

int DoubleNumber (int y)
{
return (y * 2);
}

int main()
{
using namespace std;
cout << "Enter a number: "; // ask user for a number
int z;
cin >> z; // read number from console and store it
cout << "You entered " << z << endl;
cout << DoubleNumber (z) << endl;
return 0;
}

So, your first version was

1
2
3
4
5
 
int DoubleNumber(int z)
{
    ...
}


right? For your function (DoubleNumber), z is a local variable. The value of z in the main function is being passed by value, which means that the value of z (in main) won't change, but DoubleNumber will still "x2" whatever value you call it with and print it to the user. It doesn't matter what identifier you use as long as it's valid.
When you call a function it passes the value of the argument to the function's parameter. In the case of your function, what is happening is you are telling the compiler that you want to call DoubleNumber with the value contained in z passed to its parameter. Once execution passes to the function int y is created and initialized with the value that was contained in z and the function executes its code. (Note: this is for passing by value, passing by reference operates a bit differently.)

When you name parameters and other variables in a function the same as variables external to the function, the variables in the function take precedence or "hide" the external ones. This is called scope and if you are learning about functions you should be seeing some lessons about scope soon. If not try reading up on it as it's a pretty important aspect of C++ to get straight.
Last edited on
Thanks for the quick replies, yes, I was using (int z) for the first run.
Also I should have mentioned I am using VS2008 Standard. Ed.
Al.
Topic archived. No new replies allowed.