C++ Function

In C++, a function is a block of code that performs a specific task. It allows you to write code once and reuse it wherever needed, helping to make the program more modular and organized.

Syntax:


return_type function_name(parameters) {
    // Function body
    return value;  // Return statement (if needed)
}

Explanation:

1. Return Type: Specifies the type of value the function will return (e.g., int, float, void for no return).

2. Function Name: A unique identifier for the function (e.g., addNumbers, printMessage).

3. Parameters (Optional): Inputs to the function that allow it to process data. These are written inside parentheses after the function name.

4. Body: The block of code that defines what the function does, enclosed in curly braces { }.

Example:


#include <iostream>
using namespace std;

// define the function
void display() {
    cout << "Hello, World!" << endl;
}

int main() {
    display(); // Function call
    return 0;
}

Output:

Hello, World!

Explanation:

1. Return type: void (no return value)

2. Function name: display

3. Parameters: None

4. Body: Prints a message