A First Look at Function
Declaring and Defining a Function
General form:
return_type name (formal arguments); // declaration
return_type name (formal arguments) body // definition
Formal arguments (also called parameters), format is
type1 name1, type2 name2, ...
Make return type void if you don't want to return anything
body is a block (or a try block)
Example:
double f(int a, double d) { return a*d; }
Calling a Function
Recall
double f(int a, double d) { return a*d; }
To call a function:
name (actual arguments)
Actual arguments format is
argname1, argname2, ...
Do not include types!
Example:
int x = 2;
double y = 5.0;
cout << f(x,y); // prints out 10.0

Function Placement
Functions must be declared in the .cpp file before they are called.
So if a function is called in the main function, then it must be declared before main.
It can be defined later, as long as it is declared before it is called.
You cannot define functions inside other functions
Well, lambdas are allowed…
Last updated
Was this helpful?