Functions are one of the most important concepts in C++ programming.
A function is a reusable block of code designed to perform a specific task.
Instead of writing the same code repeatedly, you can create a function and call it whenever needed.
1. Function Declaration
A function declaration tells the compiler about the function name, return type, and parameters before the function is used.
Syntax:
return_type function_name(parameters);
Example:
#include <iostream>
using namespace std;
void greet();
int main() {
greet();
return 0;
}
void greet() {
cout << "Hello, Welcome to C++!";
}
Output:
Hello, Welcome to C++!
2. Function Definition
A function definition contains the actual code that executes when the function is called.
void display() {
cout << "Learning C++ Functions";
}Here:
•
void represents the return type.•
display is the function name.•
{ } contains the function body.3. Function Calling
A function call executes the statements inside a function.
void message() {
cout << "Hello World!";
}
int main() {
message();
return 0;
}Output:
Hello World!
4. Function Parameters
Parameters are variables that receive values when a function is called.
void greet(string name) {
cout << "Hello " << name;
}
int main() {
greet("John");
return 0;
}Output:
Hello John
Here,
name is a parameter and "John" is the argument passed to the function.5. Return Values
A function can return a value using the
return statement.int add(int a, int b) {
return a + b;
}
int main() {
int result = add(10, 20);
cout << result;
return 0;
}Output:
30
6. Pass by Value
In pass by value, a copy of the variable is passed to the function.
Changes made inside the function do not affect the original variable.
void change(int x) {
x = 100;
}
int main() {
int number = 50;
change(number);
cout << number;
return 0;
}Output:
50
7. Pass by Reference
In pass by reference, the function receives a reference to the original variable.
Changes made inside the function affect the original variable.
void change(int &x) {
x = 100;
}
int main() {
int number = 50;
change(number);
cout << number;
return 0;
}Output:
100
8. Default Arguments
Default arguments allow you to assign default values to function parameters.
If an argument is not provided during the function call, the default value is used.
void greet(string name = "Guest") {
cout << "Hello " << name;
}
int main() {
greet();
return 0;
}Output:
Hello Guest
You can also override the default value:
greet("John");9. Function Overloading
Function overloading allows multiple functions to have the same name but different parameter lists.
int add(int a, int b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
int main() {
cout << add(10, 20) << endl;
cout << add(10, 20, 30);
return 0;
}Output: