How to Define a Function in C++

Formulas & functions · Updated November 22, 2026

Defining a function in C++ lets you package a block of code under a name so you can call it repeatedly, pass it data, and get results back. It is the core of organizing any non-trivial program. Before you start, you need a C++ compiler (like g++ or clang) and a text editor or IDE (Visual Studio, CLion, VS Code with a C++ extension). You should also know basic syntax: variables, data types, and how to compile and run a simple program.

What You’ll Need

  • A C++ compiler (g++, clang++, or MSVC).
  • A text editor or IDE.
  • Basic familiarity with writing and compiling a .cpp file (e.g., g++ program.cpp -o program).

Step-by-Step

  1. Decide the function’s purpose and signature. Ask: what inputs does it need (parameters) and what does it return? For example, a function that adds two integers takes two int parameters and returns an int.
  2. Write the function definition. The general form is: return_type function_name(parameter_list) { body }. Place it either before main() or in a header file. For a simple add function, write:
    int add(int a, int b) {
        return a + b;
    }

    The return type is int, the name is add, parameters are int a and int b, and the body returns their sum.

  3. If the function returns nothing, use void. Example: void printMessage() { std::cout << "Hello\n"; }. No return statement is required (though you can use return; to exit early).
  4. Add parameter types and names. Each parameter must have a type. If you don't need a parameter, leave the parentheses empty: int getValue(). In modern C++, you can also write int getValue() (do not use void inside the parentheses unless you are writing C-style code).
  5. Include necessary headers. If your function uses std::cout, std::cin, or other standard library features, add #include <iostream> at the top of your file. For math functions, #include <cmath>.
  6. Call the function from main(). After defining it, invoke it by name with arguments. Example:
    int main() {
        int result = add(3, 4);
        std::cout << result; // prints 7
        return 0;
    }

    Make sure the function is defined before the call, or provide a forward declaration.

  7. If you define the function after main(), add a forward declaration. This tells the compiler the function exists. Place a prototype (just the signature with a semicolon) before main():
    int add(int a, int b); // declaration
    
    int main() { ... }
    
    int add(int a, int b) { ... } // definition
  8. Compile and test. Save the file as program.cpp and compile with g++ program.cpp -o program (or your compiler's equivalent). Run it and check the output. If you get errors, read them carefully—they often point to the exact line.

Common Mistakes

  • Forgetting the return type. Every function must specify a return type (or void). Writing add(int a, int b) without int is a syntax error.
  • Mismatched parameter types. If you call add(3.5, 2) but the function expects int, the compiler will either truncate or warn. Use the correct types or overload the function.
  • Missing semicolon after a forward declaration. The prototype must end with a semicolon: int add(int a, int b);.
  • Defining a function inside another function. C++ does not allow nested function definitions (except lambdas). Define it at namespace scope.
  • Using void in the parameter list when you mean no parameters. In C++, int f(void) is legal but considered old-style; prefer int f().

Tips

  • Use meaningful names. calculateAverage is better than calc.
  • Keep functions short and focused. If a function does more than one thing, split it.
  • Pass by reference for large objects. Use const std::string& instead of std::string to avoid copying. For output parameters, use non-const references.
  • Use const for parameters you don't modify. Example: int getLength(const std::string& s).
  • Consider default arguments. You can specify defaults in the declaration: int add(int a, int b = 0); then call add(5).
  • Use function overloading for similar tasks. You can have two functions with the same name but different parameter lists.

Troubleshooting

  • Compiler error: 'function' was not declared in this scope. This means the function is not defined before the call. Either move the definition above main() or add a forward declaration.
  • Linker error: undefined reference to 'add(int, int)'. This happens when you declared the function but never defined it. Make sure the definition exists exactly with the same signature.
  • Compiler warns about unused parameter. If you don't use a parameter, omit its name in the definition (e.g., int f(int)) or comment it out.
  • Unexpected output when passing floats. If you pass 3.5 to an int parameter, it is truncated to 3. Use double parameters if you need fractional values.
  • Function call with too many or too few arguments. Count the parameters in the definition and match them in the call.

Frequently Asked Questions

Q: Can I define a function inside main()?
No, standard C++ does not allow nested function definitions. Use a lambda if you need a local function.

Q: What is the difference between a function declaration and definition?
A declaration (prototype) tells the compiler the function's name, return type, and parameters. A definition includes the body. You can have many declarations but only one definition.

Q: How do I return multiple values?
You can return a std::pair, std::tuple, or a struct. Alternatively, use reference parameters to output values.

Q: What does void mean in a function?
It means the function does not return a value. You can still use return; to exit early.

Q: Can I change a parameter's value inside the function?
Yes, but it only changes the local copy unless you pass by reference (int&). For example, void increment(int& x) { x++; } modifies the original variable.

Q: What is function overloading?
It is defining multiple functions with the same name but different parameter types or counts. The compiler picks the correct one based on the arguments.

Related

Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.

More in Formulas & functions

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.