0

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

Dharman
  • 30,962
  • 25
  • 85
  • 135
haloum
  • 3
  • 2
  • Check out the intro books on c++ for people w/o prior programming experience. https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282 – doug Oct 07 '22 at 18:50
  • 1st you need to describe (in writing) what the function should do. Then add (again in writing not code), how it should be used by another part of the program. When you have done this you will have answered your own question. We can't do this for you as we don't know what you want the function to do. – Richard Critten Oct 07 '22 at 18:53
  • functions are quite similar amongst all programming languages. They are a way of encapsulating operations to reduce complexity. You might read the wiki entry [here](https://en.wikipedia.org/wiki/Function_(computer_programming)) and look at the examples. – doug Oct 07 '22 at 19:25
  • Some functions require extra information, that information is supplied by parameters. For example, adding two numbers requires two numbers. So the `add()` function would require two numbers (as parameters) to add. – Thomas Matthews Oct 07 '22 at 21:02

1 Answers1

0

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.

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154
  • To be pedantic, `cin` is NOT restricted to reading from the keyboard, it reads from `stdin` which can be a console, file, pipe, or special device... and additionally the program can detach `cin` from `stdin` and attach any custom streambuf in its place. But the point is valid, having a function that insists on doing stream I/O, even with redirection, is much less flexible than one which accepts its input as a parameter. – Ben Voigt Oct 07 '22 at 21:35