Skip to Content
FunctionsC++ Functions

C++ Functions

Functions are reusable blocks of code that perform specific tasks. They help organize code, make it more readable, and avoid repetition.

What is a Function?

A function is a group of statements that together perform a task. Every C++ program has at least one function, which is main().

Basic Function Syntax

returnType functionName(parameters) { // function body return value; }

Components:

  • returnType: The data type of the value the function returns (int, double, void, etc.)
  • functionName: A descriptive name for the function
  • parameters: Input values the function receives (optional)
  • return: Sends a value back to the caller (not needed for void functions)

Simple Function Example

#include <iostream> using namespace std; // Function declaration void greet() { cout << "Hello, World!" << endl; } int main() { greet(); // Function call return 0; }

Output:

Hello, World!

Functions with Parameters

Parameters allow you to pass data to functions:

#include <iostream> using namespace std; void greetUser(string name) { cout << "Hello, " << name << "!" << endl; } int main() { greetUser("Alice"); greetUser("Bob"); return 0; }

Output:

Hello, Alice! Hello, Bob!

Functions with Return Values

Functions can return values to the caller:

#include <iostream> using namespace std; int add(int a, int b) { return a + b; } int main() { int result = add(5, 3); cout << "5 + 3 = " << result << endl; return 0; }

Output:

5 + 3 = 8

Topics in This Section

Learn more about advanced function topics:

Function Prototypes (Declaration)

You can declare a function before defining it:

#include <iostream> using namespace std; // Function prototype (declaration) int multiply(int x, int y); int main() { int result = multiply(4, 7); cout << "4 * 7 = " << result << endl; return 0; } // Function definition int multiply(int x, int y) { return x * y; }

Void Functions

Functions that don’t return a value use the void keyword:

#include <iostream> using namespace std; void printLine() { cout << "----------------------" << endl; } int main() { printLine(); cout << "Hello, Functions!" << endl; printLine(); return 0; }

Output:

---------------------- Hello, Functions! ----------------------

Best Practices

  1. Use descriptive names: calculateArea() is better than calc()
  2. Keep functions small: Each function should do one thing well
  3. Use const references for large objects you don’t want to modify
  4. Document your functions: Add comments explaining what they do
  5. Avoid global variables: Pass data through parameters instead

Functions are fundamental to writing clean, maintainable C++ code!

Last updated on