在函数中声明变量

时间:2018-10-04 19:48:50

标签: c++

int function(int a, int b){
    a = a*b;
    return(a);
}

这是一个非常愚蠢的问题,但是,如果我通过4和2。 为什么不需要声明 a

1 个答案:

答案 0 :(得分:1)

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
}

请注意,以上示例中的“ a”和“ b”现在已销毁。它们仅存在于函数内部,并且每次您使用传入的新值调用function()时都会重新创建。您无法在此函数之外的任何地方调用在此函数中使用的'a'和'b',因为它们在此功能之外不存在。这意味着您可以在此函数之外声明另一个“ int a”和“ int b”。

如果我在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.