0% found this document useful (0 votes)
7 views4 pages

Chapter 4 Functions CPP

C++
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views4 pages

Chapter 4 Functions CPP

C++
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Chapter 4: Function and Passing Arguments to Function

4.1 Definition of Function

A function is a block of code designed to perform a specific task. Functions improve modularity and code re

Example:

#include <iostream>

using namespace std;

void greet() {

cout << "Hello, World!" << endl;

int main() {

greet();

return 0;

4.2 Declaration of Function

A function declaration tells the compiler about the function's name, return type, and parameters.

Example:

#include <iostream>

using namespace std;

int add(int, int); // Declaration

int main() {

cout << "Sum: " << add(5, 3) << endl;

return 0;
}

int add(int a, int b) {

return a + b;

4.3 Passing Value of a Function by Value

In pass-by-value, the actual value is passed. Changes inside the function do not affect the original variable

Example:

#include <iostream>

using namespace std;

void modify(int x) {

x = x + 10;

int main() {

int a = 5;

modify(a);

cout << "Value after modify: " << a << endl; // Output: 5

return 0;

4.4 Passing Value of a Function by Reference

In pass-by-reference, the address of the variable is passed, allowing modifications to the original value.

Example:

#include <iostream>

using namespace std;


void modify(int &x) {

x = x + 10;

int main() {

int a = 5;

modify(a);

cout << "Value after modify: " << a << endl; // Output: 15

return 0;

Additional Example 1: Function Returning a Value

#include <iostream>

using namespace std;

int multiply(int a, int b) {

return a * b;

int main() {

cout << "Product: " << multiply(4, 5) << endl; // Output: 20

return 0;

Additional Example 2: Using Default Arguments

#include <iostream>

using namespace std;

int add(int a, int b = 10) { // b has a default value

return a + b;

}
int main() {

cout << add(5) << endl; // Output: 15

cout << add(5, 20) << endl; // Output: 25

return 0;

You might also like