C++ Multiple Function Parameters
In this page:
Declaring Multiple Parameters
Multiple parameters are declared inside a function's parentheses, separated by commas, each with its own type and name, letting a single function accept several pieces of input at once.
Example: Declaring Multiple Parameters
#include <iostream>
#include <string>
void showInfo(std::string name, int age) {
std::cout << name << " is " << age << std::endl;
}
int main() {
showInfo("Alex", 30);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Matching Arguments by Position
When a function is called, each argument is matched to the corresponding parameter by its position in the list, not by name, so the order arguments are passed in matters.
Example: Matching Arguments by Position
#include <iostream>
void divide(int a, int b) {
std::cout << a << " / " << b << " = " << a / b << std::endl;
}
int main() {
divide(10, 2);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Parameters of Different Types
A function's parameters don't all need to be the same type; mixing int, double, string, and other types within one parameter list is common and fully supported.
Example: Parameters of Different Types
#include <iostream>
#include <string>
void printOrder(std::string item, double price, int quantity) {
std::cout << quantity << "x " << item << " at $" << price << std::endl;
}
int main() {
printOrder("Book", 12.5, 3);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Using Multiple Parameters Together
Multiple parameters are often combined inside the function body to compute a result, such as multiplying a quantity by a price or comparing two values against each other.
Example: Using Multiple Parameters Together
#include <iostream>
double totalCost(double price, int quantity) {
return price * quantity;
}
int main() {
std::cout << totalCost(9.99, 3) << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Too Many or Too Few Arguments
Calling a function with the wrong number of arguments -- too few or too many -- is a compile-time error in C++, since the compiler checks that every call matches the function's declared parameter list.
Example: Too Many or Too Few Arguments
#include <iostream>
void add(int a, int b) {
std::cout << a + b << std::endl;
}
int main() {
add(2, 3);
// add(2); // compile-time error: too few arguments
// add(2, 3, 4); // compile-time error: too many arguments
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 13 topics to unlock
0/13 topics done
Complete these topics first:
- C++ Functions Introduction
- C++ Function Parameters
- C++ Multiple Function Parameters
- C++ Passing by Reference
- C++ Passing Structures to Functions
- C++ Return Values
- C++ Function Overloading
- C++ Default Arguments
- C++ Recursion
- C++ Inline Functions
- C++ Lambda Functions
- C++ Scope & Lifetime
- C++ Math Functions