C++ Functions
In C++, functions are blocks of code that perform a specific task. They allow you to break down your program into smaller, manageable parts, and can be called multiple times from different parts of your program.
1. Declaring and Defining Functions
Example of declaring and defining a function:
#include <iostream>
// Function declaration (prototype)
void greet();
int main() {
// Function call
greet();
return 0;
}
// Function definition
void greet() {
std::cout << "Hello, World!" << std::endl;
}
2. Function Parameters
Example of a function with parameters:
#include <iostream>
// Function declaration with parameters
void displaySum(int a, int b);
int main() {
int x = 5, y = 3;
// Function call with arguments
displaySum(x, y);
return 0;
}
// Function definition
void displaySum(int a, int b) {
std::cout << "Sum: " << (a + b) << std::endl;
}
3. Function Return Values
Example of a function with a return value:
#include <iostream>
// Function declaration with return type
int multiply(int a, int b);
int main() {
int x = 4, y = 6;
// Function call and output the result
std::cout << "Product: " << multiply(x, y) << std::endl;
return 0;
}
// Function definition
int multiply(int a, int b) {
return a * b;
}
4. Function Overloading
Example of function overloading:
#include <iostream>
#include <string>
// Function overloading
void display(int num);
void display(std::string message);
int main() {
int number = 42;
std::string greeting = "Hello, Function Overloading!";
// Function calls
display(number);
display(greeting);
return 0;
}
// Function definitions
void display(int num) {
std::cout << "Number: " << num << std::endl;
}
void display(std::string message) {
std::cout << message << std::endl;
}
Conclusion
Functions in C++ allow you to organize your code into reusable blocks, enhancing code clarity and maintainability. This chapter covered basic function declaration, defining functions, using parameters and return values, and function overloading. Understanding functions enables you to design modular and efficient C++ programs by breaking down tasks into smaller, manageable units.