Programming Fundamentals (COMP1112) : Function in C++
Programming Fundamentals (COMP1112) : Function in C++
(COMP1112)
Function in C++
Course Instructor
Dr. Aftab Akram
PhD CS
Assistant Professor
Department of Information Sciences, Division of Science &
Technology
University of Education, Lahore
Functions
• A function is a block of code that performs a specific
task.
• Suppose we need to create a program to create a circle
and color it.
• We can create two functions to solve this problem:
• a function to draw the circle
• a function to color the circle
• Dividing a complex problem into smaller chunks makes
our program easy to understand and reusable.
• There are two types of function:
• Standard Library Functions: Predefined in C++
• User-defined Function: Created by users
C++ 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.
Using Functions in C++
• Three things needed for using functions in C++:
• Function Prototype
• Function Definition
• Function Call
• Function Declaration is made before main().
• Function Definition is made after main().
• Function Call is made inside main().
• Function Declaration and Function Definition can
be combined, but it must be placed before
main().
C++ Function Prototype
• The syntax to declare a function prototype is:
• returnType functionName (parameter1,
parameter2,...);
• Here's an example of a function prototype
declaration without definition.
//function declaration (without definition)
void greet(void);
void add(int,int);
int addTwoNums(int,int);
• Note that at this stage, only need to mention input
datatypes. Exact names of variables are not
required.
C++ Function Prototype
C++ Function Prototype with
Definition
• The syntax to declare a function prototype is:
returnType functionName (parameter1, parameter2,...)
{
// function body
}