Course Content
C++ Introduction
C++ Introduction
Functions 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:
main
#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:
main
#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:
main
#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); }
Thanks for your feedback!