. Functions Explained
Functions are a fundamental part of C++ programming, allowing you to encapsulate a block of code that can be called and reused multiple times. Understanding functions is crucial for writing modular, maintainable, and efficient code. This section will cover the key concepts related to functions in C++.
Key Concepts
1. Function Declaration and Definition
A function in C++ consists of two parts: the declaration and the definition. The declaration (also known as the function prototype) tells the compiler about the function's name, return type, and parameters. The definition contains the actual code that the function executes.
Example:
#include <iostream> using namespace std; // Function declaration int add(int a, int b); int main() { int result = add(3, 4); cout << "The sum is: " << result << endl; return 0; } // Function definition int add(int a, int b) { return a + b; }
2. Function Parameters and Arguments
Functions can take parameters, which are variables listed inside the parentheses in the function declaration. When the function is called, arguments are the actual values passed to the function. Parameters act as placeholders for these arguments.
Example:
#include <iostream> using namespace std; void greet(string name) { cout << "Hello, " << name << "!" << endl; } int main() { greet("Alice"); greet("Bob"); return 0; }
3. Function Overloading
Function overloading allows you to define multiple functions with the same name but different parameters. The compiler determines which function to call based on the number and type of arguments passed.
Example:
#include <iostream> using namespace std; int add(int a, int b) { return a + b; } double add(double a, double b) { return a + b; } int main() { cout << "Sum of integers: " << add(3, 4) << endl; cout << "Sum of doubles: " << add(3.5, 4.5) << endl; return 0; }