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.
#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; }
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.
#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; }
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!
#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; }
return KeywordIf 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.
#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; }
What is the actual value passed to a function called?