1 Functions in C++
1.1 Purpose
Functions encapsulate specific operations, reducing code duplication and improving modularity.
1.2 Defining and Calling Functions
Syntax for Definition:
return_type function_name(parameter list) { functon body return expression; }
Example: Sum of Two Integers
int add(int a, int b) {
// a and b are formal parameters
return a + b;
}
Calling a Function:
function_name(argument list);
int main() {
int x = 4, y = 5;
int result = add(x, y); // x and y are actual arguments
cout << result;
return 0;
}
1.3 Pass by Value
- During a function call, the values of actual arguments are copied into formal parameters.
- Modifying formal parameters does not affect actual arguments.
#include<iostream>
using namespace std;
// Function to swap two numbers using pass by value
void swap(int n1, int n2) {
cout << "Before swap:\n";
cout << "n1 = " << n1 << ", n2 = " << n2 << endl; // Prints 4, 5
int temp = n1;
n1 = n2;
n2 = temp;
cout << "After swap:\n";
cout << "n1 = " << n1 << ", n2 = " << n2 << endl; // Prints 5, 4
}
int main() {
int a = 4, b = 5;
swap(a, b);
cout << "a = " << a << ", b = " << b << endl; // Prints 4, 5
return 0;
}
1.4 Common Function Patterns
- With parameters, no return value
- With parameters, with return value
- No parameters, with return value
- No parameters, no return value
1.5 Function Declaration (Prototype)
- Informs the compiler about the function's name and how to call it.
- The actual definition can appear later in the code.
- Declarations can appear multiple times; definitions only once.
#include<iostream>
using namespace std;
// Declaration: tells compiler that max exists
int max(int num1, int num2);
int main() {
int a = 4, b = 5;
int m = max(a, b);
cout << "m = " << m << endl;
return 0;
}
// Definition appears after main
int max(int num1, int num2) {
return (num1 > num2) ? num1 : num2;
}
1.6 Splitting Functions Across Files
Purpose: Improves code organization.
Steps:
- Create a header file (
.h). - Create a source file (
.cpp). - Write function declarations in the header.
- Write function definisions in the source file.
Example: Sum of Two Integers
add.h
#pragma once
int add(int num1, int num2);
add.cpp
#include "add.h"
int add(int num1, int num2) {
return num1 + num2;
}
main.cpp
#include <iostream>
#include "add.h"
using namespace std;
int main() {
int x = 4, y = 5;
int sum = add(x, y);
cout << "Sum = " << sum << endl;
return 0;
}