0% found this document useful (0 votes)
14 views25 pages

PF Week 8

The document provides an overview of functions in C++, explaining their importance in reducing code redundancy, improving modularity, and providing abstraction. It details the syntax for declaring and defining functions, as well as how to call them, and distinguishes between built-in and user-defined functions. Additionally, it covers the scope of functions, highlighting the differences between local and global functions.
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)
14 views25 pages

PF Week 8

The document provides an overview of functions in C++, explaining their importance in reducing code redundancy, improving modularity, and providing abstraction. It details the syntax for declaring and defining functions, as well as how to call them, and distinguishes between built-in and user-defined functions. Additionally, it covers the scope of functions, highlighting the differences between local and global functions.
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/ 25

Programming Fundamentals

WEEK 08

Aqsa Ijaz
Functions in C++

• A function is a block of code which only runs when it is called.

• A function is known with various names like a method or a sub-


routine or a procedure etc.

• You can pass data, known as parameters, into a function.

• Functions are used to perform certain actions, and they are


important for reusing code: Define the code once, and use it many
times.
Syntax:
Why Do We Need Functions?

• Functions help us in reducing code redundancy. If functionality is


performed at multiple places in software, then rather than writing the same
code, again and again, we create a function and call it everywhere. This
also helps in maintenance as we have to make changes in only one place if
we make changes to the functionality in future.
• Functions make code modular. Consider a big file having many lines of
code. It becomes really simple to read and use the code, if the code is
divided into functions.
• Functions provide abstraction. For example, we can use library functions
without worrying about their internal work.
A C++ function consist of two parts:

• Declaration: the return type, the name of the function, and parameters (if
any)
• Definition: the body of the function (code to be executed)
void myFunction()
{ // declaration
// the body of the function (definition)
}
Function Declaration

A function declaration tells the compiler about the number of


parameters, data types of parameters, and returns type of
function. Writing parameter names in the function declaration is
optional but it is necessary to put them in the definition.
• A function declaration has the following parts
return_type function_name( parameter list );
• For the above defined function max(), following is the function
declaration
int max(int num1, int num2);
• Parameter names are not important in function declaration only their
type is required, so following is also valid declaration
int max(int, int);
• Function declaration is required when you define a function in one
source file and you call that function in another file. In such case, you
should declare the function at the top of the file calling the function.
Note: If a user-defined function, such as myFunction() is declared after the main()
function, an error will occur:

Example
int main() {
myFunction();
return 0;
}

void myFunction() {
cout << "I just got executed!";
}

// Error
However, it is possible to separate the declaration and the
definition of the function - for code optimization.
You will often see C++ programs that have function declaration
above main(), and function definition below main(). This will
make the code better organized and easier to read:
Example
// Function declaration
void myFunction();

// The main method


int main() {
myFunction(); // call the function
return 0;
}

// Function definition
void myFunction() {
cout << "I just got executed!";
}
Example:
// C++ Program to show function that takes
// two integers as parameters and returns
// an integer
int max(int, int);

// A function that takes an int


// pointer and an int variable
// as parameters and returns
// a pointer of type int
int* swap(int*, int);

// A function that takes


// a char as parameter and
// returns a reference variable
char* call(char b);

// A function that takes a


// char and an int as parameters
// and returns an integer
int fun(char, int);
Create a Function

C++ provides some pre-defined functions, such as main(),


which is used to execute code. But you can also create your
own functions to perform certain actions.
To create (often referred to as declare) a function, specify the
name of the function, followed by parentheses ():
Syntax
void myFunction() {
// code to be executed
}

Example Explained
• myFunction() is the name of the function
• void means that the function does not have a return value. You will learn
more about return values later in the next chapter
• inside the function (the body), add code that defines what the function
should do
Calling a Function

• Declared functions are not executed immediately. They are "saved for later
use", and will be executed later, when they are called.
• While creating a C++ function, you give a definition of what the function has
to do. To use a function, you will have to call or invoke that function.
• When a program calls a function, program control is transferred to the
called function. A called function performs defined task and when it’s return
statement is executed or when its function-ending closing brace is reached, it
returns program control back to the main program.
• To call a function, you simply need to pass the required parameters along
with function name, and if function returns a value, then you can store
returned value.
Calling a Function
In the following example, myFunction() is used to print a text (the action), when it is called:
Example
//Inside main, call myFunction():
// Create a function
void myFunction() {
cout << "I just got executed!";
}

int main() {
myFunction(); // call the function
return 0;
}

// Outputs "I just got executed!"


A function can be called multiple times:

Example
void myFunction() {
cout << "I just got executed!\n";
}

int main() {
myFunction();
myFunction();
myFunction();
return 0;
}

// I just got executed!


// I just got executed!
// I just got executed!
Example
#include <iostream>
using namespace std; // function returning the max between two
// function declaration numbers
int max(int num1, int num2); int max(int num1, int num2)
{
int main () {
// local variable declaration
// local variable declaration:
int x,a,b,ret; int result;

// calling a function to get max value. if (num1 > num2)


a=100; result = num1;
b=50; else
ret = max(a, b);
result = num2;
cout << "Max value is : " << ret << endl;

return 0; return result;


} }
Practice Tasks:
Write a function named add that takes two integers as parameters and prints
their sum.

Write a function named checkSign that takes an integer as a parameter and


prints whether the number is positive, negative, or zero.

Write a function named age group that takes an integer parameter


representing a person's age and prints a message based on the age group
(e.g., child, teenager, adult).
Write a function named favoriteHobby that takes a string parameter representing a
hobby and prints a message saying it’s the user's favorite hobby.

#include <iostream>
using namespace std;

void favoriteHobby(string hobby) {


cout << "Your favorite hobby is " << hobby << "!" << endl;
}

int main() {
favoriteHobby("reading"); // Example call
return 0;
}
Types of Functions
1. Built-in Functions
2. User Defined Functions

1. Built-in Functions:
These are pre-defined functions provided by C++ libraries. They are
part of the Standard Template Library (STL) or other included
libraries.

Purpose: To perform common tasks like mathematical operations,


input/output handling, string manipulation, and more.
Some Example of UD Functions:
Math Functions: From the <cmath> library.
•sqrt(x) (square root)
•pow(x, y) (power function)
•sin(x), cos(x), etc.
I/O Functions: From the <iostream> library.
•std::cin, std::cout
String Functions: From the <string> library.
•str.length(), str.substr(start, len)

2. User-Defined Functions

These are functions created by the programmer to perform specific


tasks based on the needs of the program.

Purpose: To provide modularity, code reusability, and readability by


defining custom operations.
Scope of Functions
The area in which a function can be accessed is known as the scope
of a function. The scope of any function is determined by the place of
function declaration.

Types are:

1. Local Functions
2. Global Functions
Local Scope:
A function that is accessible only within the block in which it is
declared. Functions defined inside classes, or as inline functions,
typically have a local scope.

Example:

void main(){
void show(void);
show();
}
Global Scope:
A function defined outside of all classes, namespaces, or other
functions. It can be accessed from anywhere in the file after its
declaration.

Example:

Which we previously(examples) discussed, those are all global in


scope.

You might also like