在不同的函数中使用相同的参数
Using the same parameter in different functions
所以我对一些事情很好奇。 我有两个功能,都按照我想要的方式工作,它们如下:
//this function returns the absolute value of a number
int abs(int y) {
if (y < 0) {
return -1 * y;
}
return y;
}
//gives a random number, multiplied by x, in the range 1-y
int randomNum(int x, int y) {
srand((int)time(0));
return abs(x * rand() % y) + 1;
}
它们都可以工作,因此它们的功能不是问题。 但是,如果您注意到,它们都使用名为"int y"的参数。
我的问题是,尽管这两个功能有效,但这种不好的做法可能会让我在更复杂的程序中搞砸吗? 还是因为变量是其各自函数的局部变量而无关紧要?
我的意思是,如果我将其中一个"int y"参数更改为其他参数,这显然没什么大不了的,我只是好奇,就是这样。
我认为对于简单的程序是可以的。
但是,您应该使用与命名相同的方法来命名变量 给第一个孩子起名字。
Robert C. Martin,《Clean Code: A Handbook of Agile Software Craftsmanship》
例如,没有人喜欢阅读声明int foo(int x, int y, int z, int xx, int bb, int cc .....)
只要大
括号内有变量 { }
,它就是作用域的局部变量。一旦离开braces
它就会死亡。
现在你问的代码,
// y is declared in abs and is alive only in the abs
int abs(int y) {
if (y < 0) {
return -1 * y;
}
return y;
}
// the previous y dies here and is inaccessible.
// a new instance of y is created in randomNum and it's valid till the brace ends
int randomNum(int x, int y) {
srand((int)time(0));
return abs(x * rand() % y) + 1;
}
现在有一点可以尝试,正如Jawad Le Wywadi
所指出的那样
int main()
{
int a = 0;
++a;
{
int a = 1;
a = 42;
cout << a;
}
cout << a;
}
自己尝试一下,让我们知道您在评论中意识到了什么。
相关文章:
- 将可变参数函数的参数封装在类实例中
- QML 使用带有参数C++函数
- 使用可变参数函数作为模板参数
- 如何在C++中伪造虚拟可变参数函数模板?
- 为什么可变参数函数不适用于模板
- C++ std::functional 中的可变参数函数模板
- 可变参数函数指针的定义对于VxWorks spyLib来说不清楚
- 使用可变参数函数覆盖具有不同函数签名的虚函数
- 考虑引用和常量的可变参数函数包装器
- 使用可变参数函数将整数和/或整数数组放入单个 int 数组中
- 在可变参数函数中转发特定范围的参数
- 通过引用传递参数;函数返回类型是否必须为 VOID?
- 使用带有一个参数函数的递归找到数字的平方
- 可变参数函数模板不能很好地使用 std::function 作为参数
- 多个可变参数函数的单个模板参数包?
- 参数数据类型未知的可变参数函数
- 可变参数函数参数包扩展
- 使用模板可变参数函数将多个参数传递给另一个函数
- 对可变参数函数的递归调用的链接器错误
- 通过像printf这样的可变参数函数传递一个带有常量字符*转换函数的类