Functions in C++ - Notes
Functions in C++ - Notes
Definition
- A function
is a block of code designed to perform a specific task.
- Functions
improve code reusability, Structuring, and readability.
Structure of a Function
returnType functionName(parameterList) {
// Function body
return value; //
Optional if returnType is void
}
Types of Functions
- Built-in
Functions: Provided by libraries (e.g., sqrt()etc.).
- User-defined
Functions: Created by the programmer.
Key Components
- Return
Type: The data type of the value returned by the function (int, void,
etc.).
- Function
Name: Identifier to call the function.
- Parameters:
Inputs passed to the function.
- Function
Body: The block of code that executes the function logic.
- Return
Statement: Optional for non-void functions.
Declaration and Definition
- Declaration:
States the function's name, return type, and parameters (prototype).
- int
add(int a, int b); // Function prototype
- Definition:
Contains the actual implementation.
- int
add(int a, int b) {
- return a + b;
- }
Function Call
- Use
the function name and pass arguments.
- int
result = add(5, 10); // Function call
Function Categories
- Void
Functions: Do not return a value.
- void
display() {
- cout << "Hello!";
- }
- Value-returning
Functions: Return a value.
- int
multiply(int a, int b) {
- return a * b;
- }
Parameter Passing
- Pass
by Value: Copies the argument's value.
- Pass
by Reference: Modifies the actual argument.
- void
modify(int &x) {
- x += 10;
- }
Default Arguments
- Provide
default values for parameters.
- int
sum(int a, int b = 5) {
- return a + b;
- }
Inline Functions
- Suggested
for small, frequently used functions to avoid function call overhead.
- inline
int square(int x) {
- return x * x;
- }
Recursive Functions
- A
function that calls itself.
- int
factorial(int n) {
- if (n == 0) return 1;
- return n * factorial(n - 1);
- }
Overloaded Functions
- Multiple
functions with the same name but different parameters.
- int
add(int a, int b);
- double
add(double a, double b);
Key Advantages
- Improves
code modularity.
- Reduces
redundancy.
- Makes
debugging easier.
- Encourages
reuse of code.
Let me know if you'd like detailed examples or further
elaboration on specific points!
Program
#include <iostream>
using namespace std;
void add(int a, int b) {
cout<<a+b<<
endl;
}
int main() {
add(2,5);
return 0;
}
Overloaded functions
#include <iostream>
using namespace std;
// Overloaded functions
int multiply(int a, int b) {
return a * b;
}
double multiply(double a, double b) {
return a * b;
}
int main() {
cout <<
"Integer multiplication: " << multiply(3, 4) << endl; //
Calls int version
cout <<
"Double multiplication: " << multiply(3.5, 4.5) << endl;
// Calls double version
return 0;
}
Comments
Post a Comment