Search⌘ K
AI Features

Parameters

Explore how parameters are used to pass data between functions in C++, including the rules for matching order and types. Learn to apply default parameters for flexibility and understand variable scope to manage accessible data within and outside functions. This lesson helps you write functions correctly and avoid common errors, setting a foundation for effective C++ programming.

Parameters syntax

Parameters are how data is passed between functions through the call of the function.

We learned earlier that we list the data we want to pass to a function in the call between the ( ). The order of the list is determined by the function definition. The first parameter in the list will be assigned to the variable listed first in the function definition.

Note: In most cases, we must have the correct number and type of data being passed to the function, or we will receive an error when you try to compile your program.

Let’s look at an example below:

C++
#include <iostream>
using namespace std;
int fctn(int arg1, int arg2);
int main()
{
int answer;
int num1 = 10;
answer = fctn(num1, 12); // num1 and 12 are arguments passed to fctn
cout << "Answer is: " << answer << endl;
}
int fctn(int arg1, int arg2) // function definition
{
cout << "num1 is assigned to arg1, value of arg1 is: "<<arg1<<endl;
cout << "12 is assigned to arg2, value of arg2 is: "<<arg2<<endl;
return arg1*arg2; // mutliplying arg1 and arg2 and returning the answer
}

As you can see ...