r/programminghelp • • Jan 26 '20

C++ Bad parameter practice

Is it bad practice to have the naming of the parameter in a function the same as the variable you are passing? For example:

void function(int num, int otherNum) { // do something }

int main() { int num = 1; int otherNum = 0;

function(num, otherNum);

return 0; }

Does having the same name effect anything?

5 Upvotes

4 comments sorted by

8

u/jedwardsol Jan 26 '20

Does having the same name affect anything?

No.

Is it bad practice to have the naming of the parameter in a function the same as the variable you are passing?

No, if it is a good name then it is a good name

void openFile(std::string filename) {}

int main()
{
     std::string filename = "numbers.dat"

     openfile(filename);

3

u/r3jjs Jan 26 '20

Its fairly normal practice to do just that. The only other option leads to horrible to read, ugly code.

If you had, for instance, writing a Point of Sale (POS) software and you had a variable called `itemPrice`, it makes sense to use `itemPrice` everywhere. The other option is to use names like `itemPrice1` or `_itemPrice` or `printFunction_itemPrice`.

Yeck!

3

u/pizzapantsu Jan 26 '20

It's totally fine.

0

u/[deleted] Jan 26 '20

I wouldn't do that, the compiler will accept it if you scope everything correctly, but you're making it easy to confuse people reading your code. Ideally i'd be using completely different names, but if that's not as descriptive as it needed to be i'd attach some relevancy to the function name on the variable name to distinguish them