Parameters and Functions

Hello everyone,

I was wondering if someone could clarify the purpose of parameters. Why are they convenient to use?

I have an assignment for my computer science class that is based on functions and parameters and need clarification so I can do the assignment on my own.


Another thing, how do you know when a function returns a value or nothing? I noticed that void is used as a function. How do you know when to use it?

I hope you guys understand what I am asking. If not, just ask and I'll clarify even further. :]

Thanks.
I was wondering if someone could clarify the purpose of parameters. Why are they convenient to use?


Parameters let you pass information to a function. Here's a simple example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void printsum(int a,int b)  // a and b are parameters
{
  cout << "The sum is " << (a + b) << endl;
}

int main()
{
  printsum(5,3);  // prints "The sum is 8"
  printsum(2,1);  // prints "The sum is 3"

  int uservar = 0;
  cout << "Enter a number and I will add 5 to it:  ";
  cin >> uservar;  // get the number from the user

  printsum(uservar,5); // prints whatever number the user input +5
}


Parameters should be preferred over global variables because it allows your functions to be more fluid and reusable. When you use global variables in a function, that function will ONLY work with those globals. If you use parameters instead, then the function can work with ANY variable that is passed to it. It isn't limited to just the one.

Another thing, how do you know when a function returns a value or nothing? I noticed that void is used as a function. How do you know when to use it?


void functions return nothing. non-void functions return something. What they return depeds on the return type, which comes before the function name:

1
2
3
4
5
6
7
void func();  // <- "void" func, means func does not return anything

int foo();  // <- "int" foo means foo returns an int

string bar();  // <- bar returns a string

// etc 

Parameters of functions are used so functions can do multiple things, not just do the same thing every time it gets called. e.g.
1
2
3
4
void print(std::string something)    //Something must be of type std::string
{    
    std::cout << something;
}


to call it:
1
2
3
4
int main()
{
    print("Hello");
}


without having parameters, you would always cout the same thing and not anything else, so it wouldn't be a multipurpose function.

Returning things lets it perform an operation. e.g.

1
2
3
4
5
6
7
8
9
10
11
12
//the 'int' at the front, says what value it returns, it it's void it returns nothing
int square(int number)   
{
    number *= number;
    return number;
}
//now the usage
int main()
{
    int x = square(4);   //It pretty much replaces the square(4) with the return value
    std::cout << x;    //it will cout 16
}
Topic archived. No new replies allowed.