There are multiple classes with the name 'function':
- Boost.Function: the Boost library
- boost::function: the function wrapper in the Boost.Function library
- std::function: the function wrapper in the C++11 STL
A function (in general) is a callable piece of code that performs a specific general task with as little information as possible (Why would you want this? Go to this page to view the purpose of using functions).
There are multiple types of functions:
- Free functions: synonym for helper function
- Helper functions
- Member functions
- Template functions
A function declaration states what a function needs and returns. A function definition states how a function uses its arguments and calculates what to return.
A function that accompanies a class (and is non-friend) is called a free function.
A Hello World is a minimal useful program that has one function: main.
#include <iostream>
int main()
{
std::cout << "Hello world\n";
return 0;
}
main returns an int (the program exit state) and needs no CppArgument.md.
Note that there is another forms of main, that does have CppArgument.md.
IsOdd is a free function that determines if the argument's value is odd, by returning a boolean that is either true or false.
bool IsOdd(const int i) noexcept
{
return i % 2 != 0;
}
- Consider using proper function design. Note: many points of advice!
- Assume that every exception that can be thrown by a function will be thrown [1]
- Implement binary operators as free functions [2]
- Do not use function template specialization [3]
- If you write iterator-based functions, provide a user-friendly interface on top of them [4]
- Short functions should be inlined and defined in headers [5]
- Large functions should be declared in headers and defined in source files [5]
- [1] Bjarne Stroustrup. The C++ Programming Language (4th edition). 2013. ISBN: 978-0-321-56384-2. Chapter 13.7. Advice. page 387: '[33] Assume that every exception that can be thrown by a function will be thrown'
- [2] Gottschling, Peter. Discovering Modern C++: An Intensive Course for Scientists, Engineers, and Programmers. Addison-Wesley Professional, 2015. Chapter 2.7.3: 'Implement binary operators as free functions'
- [3] Gottschling, Peter. Discovering Modern C++: An Intensive Course for Scientists, Engineers, and Programmers. Addison-Wesley Professional, 2015. Chapter 3.6.2.1: 'Do not use function template specialization!'
- [4] Gottschling, Peter. Discovering Modern C++: An Intensive Course for Scientists, Engineers, and Programmers. Addison-Wesley Professional, 2015. Chapter 4.1.5: 'If you write iterator-based functions, provide a user-friendly interface on top of them'
- [5] Gottschling, Peter. Discovering Modern C++: An Intensive Course for Scientists, Engineers, and Programmers. Addison-Wesley Professional, 2015. Chapter 7.2.3.2: 'Short functions should be inline and defined in headers. Large functions should be declared in headers and defined in source files'