C++ Functions

C++ Functions: Reusable Blocks of Code

In C++, a function is a block of code designed to perform a specific task. Functions allow you to break your program into smaller, modular, and reusable pieces. Instead of writing the same code multiple times, you write it once in a function and call it whenever needed!

Why Use Functions?


1. Creating and Calling a Function

To use a function, you first need to declare and define it, and then you can call (or invoke) it from main() or another function.

Syntax

returnType functionName() {
  // Code to be executed
}

Basic Function Example

#include <iostream>
using namespace std;

// Create a function void sayHello() { cout << "Hello, World!" << endl; }

int main() { // Call the function sayHello(); sayHello(); // You can call it multiple times! return 0; }


2. Function Declaration vs. Definition

In professional C++ programming, a function consists of two parts:

  1. Declaration: Tells the compiler about the function's name, return type, and parameters.
  2. Definition: Provides the actual body (code) of the function.

It is a best practice to declare functions above main() and define them below main().

Declaration and Definition

#include <iostream>
using namespace std;

// Function Declaration void printMessage();

int main() { printMessage(); // Function Call return 0; }

// Function Definition void printMessage() { cout << "Learning C++ is fun!" << endl; }


Exercise

?

Which keyword is used as the return type for a function that does not return a value?