Files
website/content/cpp/functions.md
lucasrufkahr 91628c023e a
2026-03-02 14:41:27 -06:00

47 lines
1.9 KiB
Markdown

+++
date = '2026-02-27T23:57:42-06:00'
draft = false
title = 'Functions'
layout = 'chapter'
type = 'book'
tags = 'cpp'
chapterno = 3
+++
## Documentation practice
It is a good idea to include comments along with the functions you create and should only be put within the function prototype. They should include:
- A brief description of its purpose:
- Precondition:
- The conditions that are required in order for the function to work properly.
- Postcondition:
- Only include if the final result of your function is difficult to understand by reading the code.
Make sure when creating comments, do not state the obvious. They clutter your code and make it more difficult to read your code. Only include comments to things that are complex or difficult to understand.
Example:
```c++
// Description: Returns the square of a number.
// Pre: Size of x must be less than size of int when squared.
int square(const int x);
int square(int x) {
return x * x;
}
```
Function abstraction is the ability to make a function easy to use without understanding exactly how the function works line by line. This makes it easy for other people to use your code faster. It is a good practice to make your code easy to use for other people.
## Default arguments
Suppose you want a function to occassionaly not have values for parameters explicitly define, you can set a default value for your parameters within your function.
```c++
void average(float num1 = 3, float num2 = 3, float num3 = 3);
```
In this example, the default parameters were create in the function prototype. Suppose you call the function by `average();`, then without passing and values, num1, num2, and num3 were all initialized with 3 as we have define in the prototype. Default arguments also work with just one parameter. You can set whatever parameter you want to have a default argument. Also, as long as the default argument is defined in the prototype, you should not include it in the definition.