Introduction to Functions in C++

A function in C++ is a block of code designed to perform a specific task. Functions help in breaking down complex programs into smaller, manageable, and reusable parts.

Defining and Calling a Function

Syntax

return_type function_name(parameters) {
    // Code to execute
}

Example: Simple Function

#include <iostream>

void greet() {
    std::cout << "Hello, welcome to C++ functions!" << std::endl;
}

int main() {
    greet();
    return 0;
}

Explanation: The function greet outputs a greeting message. It is called in the main function.

Key Takeaways

  • Functions help in modularizing code.
  • Functions improve code readability and reusability.
  • Call a function by its name followed by parentheses.