In C++, a function is a block of code that performs a specific task.
Functions help organize
code, make it reusable, and improve readability.
🔹 Types of Functions in C++
1. Library Functions
o Built-in functions provided by C++ (e.g., sqrt(), pow(), cout).
o Require header files like <iostream>, <cmath>, etc.
2. User-defined Functions
o Functions that you create to perform specific tasks.
🔹 Syntax of a User-defined Function
returnType functionName(parameters) {
// body of the function
}
🔹 Example: A Simple Function
#include <iostream>
using namespace std;
// Function declaration
void greet() {
cout << "Hello, Welcome to C++!" << endl;
}
int main() {
greet(); // Function call
return 0;
}
🔹 Function with Parameters and Return Value
#include <iostream>
using namespace std;
// Function to add two numbers
int add(int a, int b) {
return a + b;
}
int main() {
int result = add(5, 3); // Function call
cout << "Sum is: " << result << endl;
return 0;
}
🔹 Function Components
Part Description
Return Type Data type of the value returned (e.g., int, void)
Function Name Name used to call the function
Parameters Input values to the function (optional)
Function Body Code block that performs the task
🔹 Function Declaration / Prototype
You can declare a function before main():
int multiply(int, int); // Declaration
int main() {
cout << multiply(4, 5);
return 0;
}
int multiply(int x, int y) { // Definition
return x * y;
}
🔹 Function Overloading
Multiple functions with the same name but different parameters:
int add(int a, int b) {
return a + b;
}
float add(float a, float b) {
return a + b;
}
🔹 Inline Function (optional optimization)
inline int square(int x) {
return x * x;
}
Would you like exercises or examples related to functions (like calculator, factorial, etc.)?