Introduction to Functions in C++
Introduction Functions in C++ cplus tutorial
Functions in C++ are reusable blocks of code that perform a specific task. They help in organizing programs into smaller, manageable parts, making the code more readable, maintainable, and reusable.
Code Reusability – Write once, use many times.
Improved Readability – Break complex tasks into smaller pieces.
Easy Debugging – Isolate errors within specific functions.
Modularity – Divide logic into independent modules.
C++ has two main types of functions:
Library (Predefined) Functions
Already available in C++ libraries.
Example: sqrt(), pow(), strlen().
User-defined Functions
Created by programmers to perform specific tasks.
A function generally has three parts:
Declaration (Prototype) – Tells the compiler about the function name, return type, and parameters.
Definition – Contains the actual code.
Function Call – Used to execute the function.
returnType functionName(parameters) {
// function body
}
Example:
#include <iostream>
using namespace std;
// Function declaration
int add(int a, int b);
int main() {
int result = add(5, 3); // function call
cout << "Sum: " << result << endl;
return 0;
}
// Function definition
int add(int a, int b) {
return a + b;
}
Output:
Sum: 8
Pass by Value – Copies the actual value.
Pass by Reference – Passes the memory address, allowing modification.
Use descriptive function names.
Keep functions short and focused on one task.
Declare function prototypes before main().
Avoid using too many global variables inside functions.