W6L2-User Defined Functions
W6L2-User Defined Functions
Programming
(CS-110)
Course Instructors:
Dr. Momina Moetesum
Ms. Shakeela Bibi
1
Generally, a C/C++ function has three parts:
• Function Prototype
Syntax of Functions • Function Definition
in C/C++ • Function Call
2
Function Prototype (Declaration)
3
• return_type: It is the data type of the value
Function that the function returns. It can be any data
type int, float, void, etc. If the function does not
Prototype return anything, void is used as the return type.
• function_name: It is the identifier of the
function. Use appropriate names for the
functions that specify the purpose of the
function.
• parameter_list: It is the list of parameters that
a function expects in parentheses. A parameter
consists of its data type and name. If we don’t
want to pass any parameter, we can leave the
parentheses empty.
4
Function Return Type
• Function return type tells what type of value is returned after all
function is executed. When we don’t want to return a value, we can
use the void data type.
• Example: int func(parameter_1,parameter_2);
• The above function will return an integer value after running
statements inside the function.
• Note: Only one value can be returned from a C/C++ function. To
return multiple values, we have to use pointers or structures.
5
Function Parameters or Arguments
• Function Arguments (also known as
Function Parameters in some cases) are
the data that is passed to a function.
6
In C/C++ programming language,
functions can be called either with or
without arguments and may or might not
return values.
• Function with no arguments and no
return value
• Function with no arguments and with
return value
• Function with argument and with no
return value
• Function with arguments and with return
value
7
Function Definition
return_type function_name (para1_type para1_name, para2_type para2_name)
{
// body of the function
}
8
Function Call
• A function call is a statement that instructs the
compiler to execute the function. We use the
function name and parameters in the function
call.
• In the below example, the first sum function is
called and 10,30 are passed to the sum
function.
• After the function call sum of a and b is
returned and control is also returned back to
the main function of the program.
• Types:
• Call by Value
• Call by Reference (we will study later)
9
Examples
Examples
Examples
Acknowledgment
13