Dev Notes

Various Cheat Sheets and Resources by David Egan/Carawebs.

Beginner C++ Functions


C++
David Egan

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:

return_type functionName(parameter1_type parameter1, parameter2_type parameter2);
// or simply:
return_type functionName(parameter1_type, parameter2_type);

Specific example of function declaration:

// Declare a function that sums two float inputs
float sumInputs(float input1, float input2);

// Parameter names are not needed for function declaration, so this is also valid:
float sumInputs(float, float);

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:

return_type functionName( parameters )
{
  // Body of the function: statements
  // Function terminates either by returning or throwing an exception
}

This example doubles an input integer:

int doubleInput(int input)
{
  return input * 2;
}

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