Home > Blockchain >  What parameters should I put in functions
What parameters should I put in functions

Time:10-09

How do I know which variables to declare as parameters and which ones I should just declare inside the function?

CodePudding user response:

Let's say I want to write a function that prints a name. So you can say that the function needs information that is not in the function.

One method is to ask the User:

void print_name()
{
  std::string name;
  std::cout << "Enter name: ";
  std::cin >> name;
  std::cout << "\nname is: " << name << "\n";
}

The above function is limited in usage: a Console or User is required.

For example, if I have a list of names, I can't use the above function to print the names.

So, the function will need information from elsewhere. The information will be passed by parameter. The parameter contains information for the print function:

void print_name_from_parameter(const std::string& name)
{
  std::cout << "Name is " << name << "\n";
}

The print_name_from_parameter function is more versatile than the above print_name function. The name to print can come from anywhere, database, other computers, other devices, etc. The print_name function is restricted to inputting the name from the console (keyboard). There are many platforms that don't have a keyboard, so the name can't be input.

  • Related