0% found this document useful (0 votes)
3 views22 pages

08.Functions

The document provides an overview of functions in C++, including their definitions, types (pre-defined and user-defined), and how to create, call, and use them. It explains the structure of function declarations, parameters, return values, and the use of pointers and references in function calls. Examples illustrate the concepts, such as creating a function to find the maximum of two numbers and using pointers for pass-by-reference functionality.

Uploaded by

macarullo
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)
3 views22 pages

08.Functions

The document provides an overview of functions in C++, including their definitions, types (pre-defined and user-defined), and how to create, call, and use them. It explains the structure of function declarations, parameters, return values, and the use of pointers and references in function calls. Examples illustrate the concepts, such as creating a function to find the maximum of two numbers and using pointers for pass-by-reference functionality.

Uploaded by

macarullo
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/ 22

CCIT 10 2 – COMPUTER P ROGRAMMING 1

Functions
Source: The C++ Workshop, A New, Interactive Approach to Learning C++,
https://www.tutorialspoint.com/cplusplus/cpp_functions.htm
https://www.w3schools.com/cpp/cpp_functions.asp

C A M A R I N E S S U R P O LY T E C H N I C C O L L E G E S | C O L L E G E O F C O M P U T E R S T U D I E S
What is a Function?

C++ Function
• group of statements that together perform a task. Example: main()

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

• A function declaration tells the compiler about a function's name, return


type, and parameters.

• A function definition provides the actual body of the function.

• The C++ standard library provides numerous built-in functions that your
program can call. For example, function strcat() to concatenate two strings,
function memcpy() to copy one memory location to another location and
many more functions.

CCIT 102 – CP 1 CAMARINES SUR POLYTECHNIC COLLEGES | COLLEGE OF COMPUTER STUDIES


Function
Pre-defined Function
• These are Functions which are already defined. Any set of subroutines that
perform standard mathematical functions included in a programming
language; either included in a program at compilation time, or called when
a program is executed is called a function.

• Examples: max(), min(), sqrt(), round(), pow(),sqrt(),gcd(),toupper(),tolower()

CCIT 102 – CP 1 CAMARINES SUR POLYTECHNIC COLLEGES | COLLEGE OF COMPUTER STUDIES


Function
User-defined Function
• C++ allows the programmer to define their own function.
• A user-defined function groups code to perform a specific task and that
group of code is given a name (identifier).
• When the function is invoked from any part of the program, it all executes
the codes defined in the body of the function.

// function declaration
void greet()
{
cout << "Hello World";
}

CCIT 102 – CP 1 CAMARINES SUR POLYTECHNIC COLLEGES | COLLEGE OF COMPUTER STUDIES


Function
Defining a Function
• The general form of a C++ function definition is as follows −
return_type function_name( parameter list ) {
body of the function
}

A C++ function definition consists of a function header and a function body. Here
are all the parts of a function −

•Return Type − A function may return a value. The return_type is the data type of the
value the function returns. Some functions perform the desired operations without
returning a value. In this case, the return_type is the keyword void.

•Function Name − This is the actual name of the function. The function name and the
parameter list together constitute the function signature.

CCIT 102 – CP 1 CAMARINES SUR POLYTECHNIC COLLEGES | COLLEGE OF COMPUTER STUDIES


Function
Defining a Function
• The general form of a C++ function definition is as follows −
return_type function_name( parameter list ) {
body of the function
}

A C++ function definition consists of a function header and a function body. Here
are all the parts of a function −
•Parameters − A parameter is like a placeholder. When a function is invoked, you pass
a value to the parameter. This value is referred to as actual parameter or argument.
The parameter list refers to the type, order, and number of the parameters of a
function. Parameters are optional; that is, a function may contain no parameters.

•Function Body − The function body contains a collection of statements that define
what the function does.

CCIT 102 – CP 1 CAMARINES SUR POLYTECHNIC COLLEGES | COLLEGE OF COMPUTER STUDIES


Function
Example
Following is the source code for a function called max(). This function takes two
parameters num1 and num2 and return the biggest of both −

// function returning the max between two numbers int


max(int num1, int num2) {
// local variable declaration
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}

CCIT 102 – CP 1 CAMARINES SUR POLYTECHNIC COLLEGES | COLLEGE OF COMPUTER STUDIES


Function
Function Declaration
• A function declaration tells the compiler about a function name and how to
call the function. The actual body of the function can be defined separately.

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 a 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.a
CCIT 102 – CP 1 CAMARINES SUR POLYTECHNIC COLLEGES | COLLEGE OF COMPUTER STUDIES
Function
Create a Function
• C++ provides some pre-defined functions, such as main(). 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 ():

void myFunction() {
// code to be executed
}

•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

CCIT 102 – CP 1 CAMARINES SUR POLYTECHNIC COLLEGES | COLLEGE OF COMPUTER STUDIES


Function
Calling a Function
• 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.

CCIT 102 – CP 1 CAMARINES SUR POLYTECHNIC COLLEGES | COLLEGE OF COMPUTER STUDIES


Function

Calling a Function
• In the following example, myFunction() is used to print a text (the
action), when it is called:

// Create a function
void myFunction() {
cout << "I just got executed!";
}

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

// Outputs "I just got executed!"

CCIT 102 – CP 1 CAMARINES SUR POLYTECHNIC COLLEGES | COLLEGE OF COMPUTER STUDIES


C++ Function Parameters

Parameters and Arguments


• Information can be passed to functions as a parameter. Parameters
act as variables inside the function.

• Parameters are specified after the function name, inside the


parentheses. You can add as many parameters as you want, just
separate them with a comma:

void functionName(parameter1, parameter2, parameter3) {


// code to be executed
}

CCIT 102 – CP 1 CAMARINES SUR POLYTECHNIC COLLEGES | COLLEGE OF COMPUTER STUDIES


C++ Function Parameters
Example:
void myFunction(string fname) {
cout << fname << " Refsnes\n";
}

int main() { The following example has a function that


myFunction("Liam"); takes a string called fname as parameter.
myFunction("Jenny"); When the function is called, we pass along a
myFunction("Anja"); first name, which is used inside the function
return 0; to print the full name:
}

// Liam Refsnes
// Jenny Refsnes
// Anja Refsnes

CCIT 102 – CP 1 CAMARINES SUR POLYTECHNIC COLLEGES | COLLEGE OF COMPUTER STUDIES


C++ The Return Keyword
Return Values

int myFunction(int x) {
return 5 + x;
}
The void keyword, used in the previous
examples, indicates that the function should
int main() { not return a value. If you want the function to
cout << myFunction(3); return a value, you can use a data type (such
return 0; as int, string, etc.) instead of void, and use
} the return keyword inside the function:

// Outputs 8 (5 + 3)

CCIT 102 – CP 1 CAMARINES SUR POLYTECHNIC COLLEGES | COLLEGE OF COMPUTER STUDIES


C++ The Return Keyword
Return Values

int myFunction(int x, int y) {


return x + y;
}

int main() { This example returns the sum of a


cout << myFunction(5, 3); function with two parameters
return 0;
}

// Outputs 8 (5 + 3)

CCIT 102 – CP 1 CAMARINES SUR POLYTECHNIC COLLEGES | COLLEGE OF COMPUTER STUDIES


C++ The Return Keyword
Return Values

int myFunction(int x, int y) {


return x + y;
}

int main() { You can also store the result in a


int z = myFunction(5, 3); variable
cout << z;
return 0;
}
// Outputs 8 (5 + 3)

CCIT 102 – CP 1 CAMARINES SUR POLYTECHNIC COLLEGES | COLLEGE OF COMPUTER STUDIES


C++ Reference
Creating References
A reference variable is a "reference" to an existing variable, and it is created with
the & operator:

Now, we can use either the variable name food or the reference name meal to refer to
the food variable:

You cannot have NULL references. You must


always be able to assume that a reference is
connected to a legitimate piece of storage.

CCIT 102 – CP 1 CAMARINES SUR POLYTECHNIC COLLEGES | COLLEGE OF COMPUTER STUDIES


C++ Functions - Pass By Reference
Pass By Reference
void swapNums(int &x, int &y) {
int z = x;
x = y;
y = z;
} You can also pass a reference to the
function. This can be useful when you
int main() { need to change the value of the
int firstNum = 10;
arguments:
int secondNum = 20;

cout << "Before swap: " << "\n";


cout << firstNum << secondNum << "\n";

// Call the function, which will change the values of firstNum


and secondNum
swapNums(firstNum, secondNum);

cout << "After swap: " << "\n";


cout << firstNum << secondNum << "\n";

return 0;
}
CCIT 102 – CP 1 CAMARINES SUR POLYTECHNIC COLLEGES | COLLEGE OF COMPUTER STUDIES
C++ Pointers
Some C++ tasks are performed more easily with pointers, and other C++ tasks,
such as dynamic memory allocation, cannot be performed without them.

every variable is a memory location and every memory location has its address defined
which can be accessed using ampersand (&) operator which denotes an address in
memory.

Consider the following which will print the address of the variables defined −

CCIT 102 – CP 1 CAMARINES SUR POLYTECHNIC COLLEGES | COLLEGE OF COMPUTER STUDIES


C++ Pointers
What are Pointers?
A pointer is a variable whose value is the address of another variable. Like any
variable or constant, you must declare a pointer before you can work with it. The
general form of a pointer variable declaration is −

Here, type is the pointer's base type; it must be a valid C++ type and var-name is the
name of the pointer variable. Following are the valid pointer declaration −

CCIT 102 – CP 1 CAMARINES SUR POLYTECHNIC COLLEGES | COLLEGE OF COMPUTER STUDIES


Using Pointers in C++
There are few important
operations, which we will do with
the pointers very frequently.

(a) We define a pointer variable.

(b) Assign the address of a variable


to a pointer.

(c) Finally access the value at the


address available in the pointer
variable. This is done by using
unary operator * that returns the
value of the variable located at the
address specified by its operand.

The following example makes use


of these operations −

CCIT 102 – CP 1 CAMARINES SUR POLYTECHNIC COLLEGES | COLLEGE OF COMPUTER STUDIES


Function Call by Pointer
// C++ program to implement
// pass-by-reference with pointers
#include <iostream>
Passing the variable address from using namespace std;
the calling function and using them
as a pointer inside the function is void f(int *x)
called the call-by-pointer. This {
method allows clearer visibility of *x = *x - 1;
functions in which the value of the }
passed variables may change. i.e.,
// Driver code
int main()
{
int a = 5;

cout << a << endl;


f(&a);
cout << a << endl;
}

CCIT 102 – CP 1 CAMARINES SUR POLYTECHNIC COLLEGES | COLLEGE OF COMPUTER STUDIES

You might also like