简体   繁体   中英

When passing by reference, should you keep the same variable name in the function?

When passing variables by reference, should you keep the same variable name in the function? Eg

int main()
{ 
const int Players = 1000;
array <double, Players> PlayerStrengths;
}

template <typename T, size_t Size>
void GeneratePlayerStrengths(array <T, Size>& _PlayerStrengths) 
{
//-- Logic here --
}

No. They may have different names.

Also, if you start a name with an underscore followed by an uppercase letter, the behavior is undefined. Don't do that.

When passing variables by reference, should you keep the same variable name in the function?

In the general case no. Or at least there is no reason why they should.

In fact I would suggest you might want to approach the issue from the other way, and say

"should the calling function use variable names that are the same as the parameter name in functions it is calling?"

In this case the answer is maybe

For instance, if an api to send a message takes a parameter named msg, you might want your calling function to use the same variable name

However, the important rule is that the variable name inside the function you are calling should make sense in the context of that function, and the variable name in the calling function should make sense in that context.

For instance:

int SendMsg( Msg& msgToSend)
{
// Serialise and transmit message

  return OK;
}


void GenerateAndSendShutdown (void)
{
   //You could call this msgToSend, but it wouldnt make the code any clearer
   Msg shutdownCmd = "Shutdown";
   SendMsg (shutdownCmd);
}

In your particular case, I would say it would make sense if they were the same.

Variable passed are of two types: formal arguments (as seen as function arguments) eg void func(int& formalarg) and actual arguments (as arguments passed while calling a function), eg func(actualarg), where actualarg may or maynot be of integer type. In case the typese differ, there has to be cast operator available from other type of actual argument to int (expected formal argument type). If two types are same, for program readability keeping the same name makes the program more elegant to be understood about the purpose provided you follow a meaningful naming convention. Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM