In C++, a function is a reusable block of code that performs a specific task. You call it by name whenever you need that task done, which keeps your program organized, readable, and free of duplicated code. This guide walks you through writing, declaring, defining, and calling your own functions in modern C++ (C++11 and later). You’ll learn the syntax, where to place each part, and how to avoid the most common pitfalls.
What You’ll Need
- A C++ compiler (GCC, Clang, or MSVC) and a text editor or IDE (Visual Studio, Code::Blocks, CLion, VS Code with a compiler).
- Basic familiarity with writing a
main()function and usingstd::coutfor output. - Understanding of data types (int, double, string, etc.) and how to declare variables.
Step-by-Step
- Decide what the function should do. Write a short comment describing its purpose, input, and output. For example:
// Returns the sum of two integers. - Choose the return type. If the function produces a value, use that type (e.g.,
int,double,std::string). If it just performs an action without returning anything, usevoid. - Name the function. Use a verb or verb-noun phrase in camelCase, like
calculateAreaorprintMessage. Avoid names that start with a digit or contain spaces. - List the parameters. Inside parentheses, declare each parameter with its type and a name, separated by commas. If there are no parameters, write
()empty. Example:(int width, int height). - Write the function definition. After the closing parenthesis, add an opening brace
{, the body (the statements that do the work), and a closing brace}. If the return type is notvoid, end withreturn value;. - Place the function correctly. If you define the function before
main(), you can call it directly. If you define it aftermain(), you must add a forward declaration (prototype) beforemain()so the compiler knows it exists. - Call the function. Inside
main()(or another function), write the function name followed by parentheses and the arguments you want to pass. Example:int result = add(3, 4);orprintMessage();. - Compile and test. Save your file with a
.cppextension, compile it, and run the program. Verify the output matches what you expect.
Here is a complete, minimal example that defines a function add and calls it from main:
#include <iostream>
// Function definition (before main)
int add(int a, int b) {
return a + b;
}
int main() {
int sum = add(5, 7);
std::cout << "Sum is: " << sum << std::endl;
return 0;
}
If you prefer to define the function after main, you need a forward declaration:
#include <iostream>
// Forward declaration (prototype)
int multiply(int x, int y);
int main() {
std::cout << multiply(3, 4) << std::endl;
return 0;
}
// Function definition after main
int multiply(int x, int y) {
return x * y;
}
Common Mistakes
- Forgetting the return statement when the function has a non-void return type. This leads to undefined behavior or compile errors.
- Mismatched parameter types when calling the function. Passing a
doublewhere anintis expected may cause implicit conversion, but passing a string where an int is expected will not compile. - Missing forward declaration when the function is defined after
main. The compiler will complain that the function is not declared. - Using the wrong return type (e.g., returning a
doublefrom anintfunction) can cause truncation. - Placing a semicolon after the function definition’s closing brace – that’s only for prototypes, not for definitions.
- Accidentally writing the function body inside
main– functions must be defined at namespace scope, not inside another function.
Tips
- Keep functions short and focused on one task. If a function is longer than 20–30 lines, consider splitting it.
- Use
constfor parameters that you don’t intend to modify, especially for references or pointers. - Pass large objects (like
std::stringor vectors) by reference (&) to avoid copying, but useconstif you only read them. - Give parameters descriptive names that indicate their purpose.
- Use default arguments for optional parameters, but only at the end of the parameter list. Example:
void greet(std::string name, std::string greeting = "Hello"). - For functions that don’t change the object (if they are member functions), mark them
const. - Prefer returning a value over using output parameters (references) unless you need to return multiple values.
Troubleshooting
- Compile error: ‘function’ was not declared in this scope. This means the function is defined after the call and you forgot the forward declaration. Add a prototype before
main. - Compile error: expected primary-expression before ‘)’ token. Usually means you called a function with no arguments but it expects some, or you used the wrong number of arguments.
- Linker error: undefined reference to ‘function’. This often happens if you declared the function but never defined it (or defined it in a separate file that wasn’t compiled). Make sure the definition exists and is compiled.
- Program prints a garbage value. Likely the function returned without a
returnstatement, or you forgot to assign the return value to a variable. Check the function body for all paths. - Function works but modifies variables unexpectedly. If you passed by reference and didn’t intend to change the original, use
constor pass by value. - Multiple definition error. If you define the same function in more than one source file, you’ll get this. Use
inlineor put the definition in a header withinline.
Frequently Asked Questions
- What is the difference between a function declaration and a definition? A declaration (prototype) tells the compiler the function’s name, return type, and parameters, but not the body. A definition includes the body. You can declare a function many times but define it only once.
- Can a function return multiple values? In C++11 and later, you can return a
std::pairorstd::tuple. Alternatively, use reference parameters (output parameters) to set multiple values. - What is function overloading? You can have multiple functions with the same name but different parameter lists (different types or number of parameters). The compiler picks the right one based on the arguments you pass.
- Do I need to include a return statement in a void function? No, but you can use
return;to exit early. It’s optional. - Can I define a function inside
main()? No, standard C++ does not allow nested function definitions. You can define a lambda (anonymous function) inside a function, but not a named function. - What does
constafter a member function mean? It means the function does not modify the object it is called on. It’s only for member functions of a class, not for free functions.
Related
- Visual Basic String Split: Syntax, Examples, and Tips
- Is Oracle Stock Going to Split? What Investors Should Know
- SQL String Split: Is It Built In Across All Databases?
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Snowflake String Functions: Examples and Practical UsesSnowflake string functions let you combine, inspect, extract, search, and transform text in SQL. For example, use CONCAT(first_name,…
- String Handling Functions in C: A Practical GuideC string-handling functions are declared in the standard header <string.h> and work with null-terminated character arrays. The most-used…
- Excel LEFT: How to Return Text Before a Specific WordTo return everything before a particular word in an Excel cell, use =TEXTBEFORE(A2,B2) in Microsoft 365, where A2…
- Rank Names in Excel: Formulas and Tie RulesIf names are in A2:A20 and their scores are in B2:B20, enter =RANK.EQ(B2,$B$2:$B$20,0) in C2 and fill it…
- XLOOKUP Spreadsheet Examples for Everyday Excel TasksXLOOKUP finds a value in one range and returns the corresponding value from another range; for example, with…
- Excel Formula to Count Cells With a Value, Blanks, or TextTo count cells that contain something in Excel, use =COUNTA(A2:A20), replacing A2:A20 with the range you want to…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.