在不同的函数中使用相同的参数

Using the same parameter in different functions

本文关键字:参数 函数      更新时间:2023-10-16

所以我对一些事情很好奇。 我有两个功能,都按照我想要的方式工作,它们如下:

//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;
}

自己尝试一下,让我们知道您在评论中意识到了什么。