int function(int a, int b){ // two variables, a and b, are declared and set equal to whatever you passed in when you called the function.
a = a*b; // now you are using the two already-declared variables
return(a); // return the value of 'a' which was declared in the first line and then modified
}
Note that ‘a’ and ‘b’ in the above example are now destroyed. They only live inside of the function and are re-created every time you call function() with new values passed in. You can’t call the ‘a’ and ‘b’ you were using in this function anywhere outside of this function, because they doesn’t exist outside of this function. This means that you can declare another ‘int a’ and ‘int b’ outside of this function.
If I call this function in main:
int oldA = 5; // declare an int called oldA and set it to 5
int oldB = 10; // declare an int called oldB and set it to 10
cout << function(oldA, oldB); // makes a copy of oldA and oldB and then uses them inside function()
// note that oldA and oldB are still 5 and 10. A copy of them was made and then
// used inside of function.
solved Declaring variable within a function [closed]