A function with parameters in C++ is a function that accepts inputs (called parameters) when it is called. These parameters allow you to pass information into the function, which it can then use to perform its task.
Syntax:
return_type function_name(parameter1, parameter2, ...) {
// Code using parameters
return value; // if the function has a return type
}
Note: parameter1, parameter2, …: These are the inputs that you provide when calling the function.
Example:
#include <iostream>
using namespace std;
// Function that takes two parameters and returns their sum
int add(int a, int b) {
return a + b; // Adds the two numbers and returns the result
}
int main() {
int result = add(10, 5); // Call function with 10 and 5 as arguments
cout << "The sum is: " << result << endl; // Output the result
return 0;
}
Explanation:
- Function name: add
- Parameters: int a and int b (the two numbers to add)
- Return Type: int (since the function returns the sum of two integers)
- Function call: add(10, 5): this passes 10 and 5 as arguments to the function.
C++ Function with Parameters – Interview Questions
Q 1: What are function parameters?
Ans: Variables passed to a function to receive input values.
Q 2: What are actual and formal parameters?
Ans: Actual parameters are passed during call; formal parameters receive them.
Q 3: What is pass by value?
Ans: A copy of variable is passed to the function.
Q 4: What is pass by reference?
Ans: Address of variable is passed using &.
Q 5: Which is faster: value or reference?
Ans: Pass by reference.
C++ function with parameters – Objective Questions (MCQs)
Q1. How do you pass parameters to a function in C++?
Q2. What is the output of the following code?
void add(int x, int y) {
cout << x + y;
}
add(3, 4);
Q3. Which of the following is TRUE about function parameters?
Q4. What happens if a function is declared with parameters but called without arguments?
Q5. Which type of parameter passing is used here?
void update(int a) { a = 10; }