Beginner C++ Functions
C++
This article is an ongoing summary of my notes on functions in C++. Please don’t assume that what you read here is accurate. For a more complete description of functions in C++, check the references presented below.
Functions in C++ provide a way to group statements. Functions consist of:
- A name
- A list of parameters (which may be zero)
- A body - which consists of statements enclosed with curly braces
In contrast to scripting languages like JavaScript and PHP, functions in C++ must be declared if they are to be used before their definition.
Every C++ programme has at least one function called main()
.
Function Declaration in C++
A function declaration specifies the function name and the type of data that it returns and accepts. The declaration is terminated with a semi-colon.
For example:
Specific example of function declaration:
Function Definition in C++
The function definition specifies the actual body of the function - the actual grouped statements. The general form of a C++ function definition:
This example doubles an input integer:
Declaration Rules
If a function is defined after it is used, it must be declared in advance. If the function is defined before it is used, the function declaration is optional. However, it is considered good practice to list function declarations at the top of the header file. If the function is defined in a header file which is included in the main programme, the function declaration is not strictly necessary since the header file is included before the function is called.
Best Practices
If a variable passed as a function parameter will not be modified in the function, it is considered best practice to declare the variable as const
so that it can’t be changed:
References
comments powered by Disqus