C++ Functions
Building reusable blocks of code
π§ What are C++ Functions?
Functions are reusable blocks of code that perform specific tasks. They help organize code, avoid repetition, and make programs easier to understand and maintain.
// This is a simple C++ function example
#include <iostream>
using namespace std;
void sayHello() {
cout << "Hello, World!" << endl;
}
int main() {
sayHello(); // Call the function
return 0;
}
Output:
Hello, World!
Key Function Concepts
Declaration
Define function name and type
int add(int a, int b);
Definition
Write the actual function code
int add(int a, int b) {
return a + b;
}
Function Call
Execute the function
int result = add(5, 3);
Return Value
Send data back to caller
return result;
πΉ Function Syntax
Every C++ function follows this basic structure:
// Function syntax
return_type function_name(parameter_list) {
// Function body
return value; // if return_type is not void
}
// Example: Function that adds two numbers
int addNumbers(int x, int y) {
int sum = x + y;
return sum;
}
Usage:
int result = addNumbers(10, 20); // result = 30
πΉ Void Functions
Void functions perform actions without returning a value, using the void keyword as their return
type. They are used for operations like printing, modifying references, or executing procedures where a
result isnβt needed. For example, void greet(string name) might output a message. Void functions
promote modularity, separate concerns, and improve code organization by encapsulating side effects. They are
essential in event handlers, I/O routines, and any task-focused operation in C++ programs.
#include <iostream>
using namespace std;
void printMessage() {
cout << "This function doesn't return anything!" << endl;
}
void greetUser(string name) {
cout << "Hello, " << name << "!" << endl;
}
int main() {
printMessage();
greetUser("Alice");
return 0;
}
Output:
This function doesn't return anything!
Hello, Alice!
πΉ Functions with Return Values
Functions returning values specify a data type (like int, double, or
bool) and use return to output results. They compute and deliver data back to
the caller, enabling composition and reuse. For instance, double areaCircle(double radius) returns the
computed area. Return values make functions versatile, support mathematical operations, state queries, and data
transformations, and are fundamental to structured programming, allowing clear input-output relationships in C++.
#include <iostream>
using namespace std;
// Returns an integer
int multiply(int a, int b) {
return a * b;
}
// Returns a double
double calculateArea(double radius) {
return 3.14159 * radius * radius;
}
// Returns a boolean
bool isEven(int number) {
return number % 2 == 0;
}
int main() {
cout << "5 * 3 = " << multiply(5, 3) << endl;
cout << "Area of circle (r=2): " << calculateArea(2.0) << endl;
cout << "Is 4 even? " << (isEven(4) ? "Yes" : "No") << endl;
return 0;
}
Output:
5 * 3 = 15
Area of circle (r=2): 12.5664
Is 4 even? Yes