在下面的 main
函数中,我调用了 circleArea()
并告诉它我想使用参数 circleRadius
。
之后,在 circleArea()
函数声明中,我将参数名称更改为 theRadius
。
据我了解,由于我在调用函数时声明了一个参数,所以当我声明函数时,它知道我想在函数中使用哪个值,并且我可以给它一个不同的名称。是真的吗?
如果是,当我想在函数中使用多个参数时会发生什么?
int main()
{
float pictureWidth, pictureHeight, pictureSurfaceArea,
circleRadius, circleSurfaceArea; // [4.4]
pictureWidth = 8.0;
pictureHeight = 4.5;
circleRadius = 5.0; // [4.7]
pictureSurfaceArea = pictureWidth * pictureHeight;
// Here we call our function
circleSurfaceArea = circleArea(circleRadius);
}
float circleArea(float theRadius) // [5.1]
{
float theArea;
theArea = 3.1416 * theRadius * theRadius; // pi times r square [5.4]
return theArea;
}
最佳答案
是的,你是对的。函数内部变量的局部名称可以是任何你想要的名称,相关的是
- 调用函数时必须对应的参数类型
- 位置(如果是第一个,第二个等等)
实际上,一旦您的代码被编译,生成的二进制文件根本就没有任何参数名称。这是合法的:
void method(int a, int b);
int main()
{
int z,x,y;
method(x,y);
method(z,y);
}
void method(int a, int b) {
//
}
参数的范围与函数的每个局部变量相同,并且只在该函数内部有效。
关于c - 为什么函数参数的名称在调用时与声明时不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14187178/