Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Functions With Arguments | Introduction to Functions
C++ Introduction
course content

Course Content

C++ Introduction

C++ Introduction

1. Getting Started
2. Variables and Data Types
3. Introduction to Operators
4. Introduction to Program Flow
5. Introduction to Functions

bookFunctions With Arguments

A function with a parameter (argument) is a function that has to work with an object from the outside the function.

Note

A function argument is a local variable created and exists only in the current function.

For example, let's create a function that divides any integer by 2:

To use such a function, you need to call it and pass an argument to it:

Here is an example:

cpp

main

copy
12345678910111213
#include <iostream> int func(int argument) { int result = argument / 2; return result; } int main() { //function calling and passing it an argument std::cout << "func() returned: " << func(10); }

You can pass multiple arguments to a function:

cpp

main

copy
1234567891011
#include <iostream> int func(int a, int b) { return a + b; //the function to sum arguments } int main() { std::cout << "sums the arguments = " << func(5, 7); }

func(5, 7) – calling a function and passing arguments to it. Arguments are passed with commas (,). You can also pass arrays:

cpp

main

copy
123456789101112131415
#include <iostream> //the size of the passed array is optional int func(int arrayForFunc[]) { return arrayForFunc[2]; //function will returned third element } int main() { int array[6] = { 75, 234, 89, 12, -67, 2543 }; //calling function std::cout << "Third element of array is: " << func(array); }

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 5. Chapter 4
some-alt