C++ Function Parameters

C++ Function Parameters and Arguments

Information can be passed to functions as a parameter. Parameters act as variables inside the function.

They are specified after the function name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma.


1. Parameters and Arguments

Passing Parameters Example

#include <iostream>
#include <string>
using namespace std;

// Function with one parameter void greetUser(string name) { cout << "Hello " << name << "!\n"; }

int main() { greetUser("Alice"); // "Alice" is the argument greetUser("Bob"); // "Bob" is the argument return 0; }


2. Default Parameter Values

You can provide a default value for a parameter by using the equals sign (=). If you call the function without passing an argument, it will use the default value.

Default Parameter Example

#include <iostream>
#include <string>
using namespace std;

void setCountry(string country = "USA") { cout << "I am from " << country << "\n"; }

int main() { setCountry("Canada"); // Outputs: I am from Canada setCountry(); // Outputs: I am from USA (uses default) return 0; }


3. Multiple Parameters

You can pass multiple parameters to a function by separating them with commas. When calling the function, ensure you pass the arguments in the exact same order!

Multiple Parameters Example

#include <iostream>
#include <string>
using namespace std;

void displayInfo(string name, int age) { cout << name << " is " << age << " years old.\n"; }

int main() { displayInfo("John", 25); displayInfo("Emma", 22); return 0; }


4. The return Keyword

If you want the function to compute a value and give it back to you, use a return type (like int, double, etc.) instead of void, and use the return keyword inside the function.

Return Value Example

#include <iostream>
using namespace std;

int addNumbers(int x, int y) { return x + y; // Returns the sum of x and y }

int main() { int result = addNumbers(5, 3); cout << "The sum is: " << result << "\n"; return 0; }


Exercise

?

What is the actual value passed to a function called?