FUNCTIONS
- A function is a block of code which can be given a name and called from anywhere in your code
- A function can be re-used anywhere on the program
- You declare a function like this
void PrintHello()
{
cout << “I study Computer Science” << endl; }
// And use it like this
PrintStudy();
- this function is to print out the sentence “I study Computer Science”
- When your function needs some additional information, they are called parameters.
Parameters
- A parameter is a variable which is used in an arrangement of program instructions to complete a task which is referred to one of the
- Arguments are values that are passed in to a function and they must be included in the declaration, in the round brackets.
- You can pass in as many arguments as you want, and they can be of any data type (e.g. int add2numbers(int num1, int num2)).
- You can also pass entire arrays, but you must indicate that it is an array in the declaration (int arrayName(arrayofints[]))
The meaning of the words an symbols used in this function:
- void means the that this function will not return anything
- PrintStudy is the name of the function is called. This name can be used used later in the program.
- () these brackets must be there with every function declaration.
- {} The code inside the function goes between those brackets, so therefore they must always be there
Returning a value:
- A function can return a value
- You must declare the type of the return value in the function declaration e.g.
– int myFunction() // Returns an int
– float myFunction() // Returns a float – Etc.
- You return a value from function with the return keyword
- A function can only return one value
Example:
int Add5and6()
{
return 5 + 6;
}
Example:
int Sum = Add5and6();