Reputation: 709
So I was curious about something. I have two functions, both work the way I want them to, and they are as follows:
//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;
}
They both work, so their functionality is not the problem. But if you'll notice, they both use a parameter called "int y."
My question is, despite the fact that these two functions work, is this bad practice that might screw me over in more complex programs? Or does it not matter because the variables are local to their respective functions?
I mean, it's obviously no big deal if I change one of the "int y" parameters to something else, I'm just curious, is all.
Upvotes: 0
Views: 1174
Reputation: 20931
I think it is okay for simple programs.
However, you should name a variable using the same care with which you name a first-born child.
Robert C. Martin, Clean Code: A Handbook of Agile Software Craftsmanship
For instance, nobody prefers to read the declaration int foo(int x, int y, int z, int xx, int bb, int cc .....)
Upvotes: 2
Reputation: 3564
Whenever there is a variable inside braces { }
, it is local to the scope. Once out of the braces
it simply dies.
Now the code that you are asking,
// 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;
}
Now a little thing to try out as pointed out by Jawad Le Wywadi
int main()
{
int a = 0;
++a;
{
int a = 1;
a = 42;
cout << a;
}
cout << a;
}
Try it yourself and let us know what do you realize in the comments.
Upvotes: 0