C++ functions
Created By: chatGPT
Functions in C++ are blocks of code that perform a specific task. They help in modularizing code, making it easier to read, maintain, and debug. A function can take inputs (called parameters) and can return a value after performing its task. Here's a breakdown of how to define and use functions in C++.
int add(int a, int b) {
return a + b;
}
int main() {
int sum = add(5, 3);
std::cout << "Sum: " << sum;
return 0;
}
Functions can also have void return types, meaning they do not return a value. This is useful for operations that perform tasks without needing to send a value back to the caller.
void greet() {
std::cout << "Hello, World!";
}
int main() {
greet();
return 0;
}
You can define default parameters for functions. This allows calling the function without specifying all parameters if you want to use a default value instead.
void display(int x, int y = 0) {
std::cout << "X: " << x << ", Y: " << y;
}
int main() {
display(5);
display(5, 10);
return 0;
}
Function Overloading allows you to create multiple functions with the same name but different parameter types or numbers. This feature is beneficial when the same operation should be performed with different types of data.
int multiply(int a, int b) {
return a * b;
}
double multiply(double a, double b) {
return a * b;
}
int main() {
std::cout << multiply(3, 4) << std::endl;
std::cout << multiply(3.5, 2.0) << std::endl;
return 0;
}
You can use function pointers to refer to functions and call them indirectly. This can be particularly useful in scenarios like callbacks and event handling.
void callbackFunction() {
std::cout << "Callback executed!";
}
int main() {
void (*functionPtr)() = callbackFunction;
functionPtr();
return 0;
}