← Back to C++ Course | Chapter 5: Functions | Lesson 3 of 13

C++ Multiple Function Parameters

A function can accept several parameters separated by commas, each with its own type, and arguments are matched to parameters by position when the function is called.

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

cpp
#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;
}

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

cpp
#include <iostream>

void divide(int a, int b) {
	std::cout << a << " / " << b << " = " << a / b << std::endl;
}

int main() {
	divide(10, 2);
	return 0;
}

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

cpp
#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;
}

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

cpp
#include <iostream>

double totalCost(double price, int quantity) {
	return price * quantity;
}

int main() {
	std::cout << totalCost(9.99, 3) << std::endl;
	return 0;
}

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

cpp
#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 run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.