OneBite.Dev - Coding blog in a bite size

Call A Function With Parameter In C++

Code snippet for how to Call A Function With Parameter In C++ with sample and detail explanation

C++ is a versatile language known for its efficiency and control over system resources and memory. Today, we’re going to explore how to call a function with a parameter in C++, to give you a better understanding of how parameters work within functions.

Code snippet for Function Call With Parameter

Our code snippet will illustrate a simple function that takes an integer as a parameter:

#include<iostream>

void printNum(int num) {
    std::cout << "Number Entered: " << num << std::endl;
}

int main() {
    int number = 10;
    printNum(number);
    return 0;
}

Code Explanation for Function Call With Parameter

Let’s break the code down to better understand how we are creating and calling a function with a parameter.

Firstly, we include the iostream header file which allows us to perform standard input and output operations:

#include<iostream>

We then define a function, printNum, which accepts one parameter, an integer:

void printNum(int num)

Inside this function, we use std::cout to print out a message to the console, appending the number that we passed in:

std::cout << "Number Entered: " << num << std::endl;

We move on to our program’s main function where we declare an integer number and assign it the value 10:

int number = 10;

Now, we are ready to call our printNum function, passing number as an argument:

printNum(number);

When this line of code executes, control is transferred to the printNum function, with number being passed to it. The printNum function then displays the number to the console. After this, control returns back to the main function where our program ends with return 0.

This is a fundamental concept of C++ that is essential to get to grips with when learning the language. The ability to create and call functions with parameters greatly enhances the flexibility and power of your code.

c-plus-plus