0% found this document useful (0 votes)
5 views66 pages

Function 4

The document provides an overview of functions in C programming, explaining their definition, advantages, types, and elements. It details the structure of user-defined functions, including function headers, bodies, calls, and declarations, along with categories of functions based on arguments and return values. Additionally, it discusses variable scope, visibility, and storage classes relevant to functions, as well as concepts like recursion and passing arrays to functions.

Uploaded by

mtijony2
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)
5 views66 pages

Function 4

The document provides an overview of functions in C programming, explaining their definition, advantages, types, and elements. It details the structure of user-defined functions, including function headers, bodies, calls, and declarations, along with categories of functions based on arguments and return values. Additionally, it discusses variable scope, visibility, and storage classes relevant to functions, as well as concepts like recursion and passing arrays to functions.

Uploaded by

mtijony2
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

Functions

Mr. Sunanda Das


Assistant Professor, Dept. of CSE, KUET
C Functions
• Block of statements that perform a particular task.
• Dividing a large program into the basic building blocks known as
function.
• The function contains the set of programming statements enclosed by
{}.
• A function can be called multiple times to provide reusability and
modularity to the C program.
• The function is also known as procedure or subroutine in other
programming languages.
Advantage of functions in C
• By using functions, we can avoid rewriting same logic/code again and
again in a program.
• We can call C functions any number of times in a program and from
any place in a program.
• We can track a large C program easily when it is divided into multiple
functions.
• Reusability is the main achievement of C functions.
Types of Functions
• There are two types of functions in C programming:

1. Library Functions: are the functions which are declared in the C


header files such as scanf(), printf(), gets(), puts(), ceil(), floor() etc.

2. User-defined functions: are the functions which are created by the C


programmer, so that it can be used many times. It reduces the
complexity of a big program and optimizes the code.
Elements of User-defined Functions
• In order to make use of a user defined function, we need to establish
three elements that are related to functions:

• Function definition
• Function call
• Function declaration
Definition of function
• A function definition, also known as function implementation shall
include the following element:

1. Function name
2. Function type
3. List of parameters
4. Local variable declarations
5. Function statements and
6. A return statement
• All the six elements are grouped into two parts:
• Function header (the first three elements) and
• Function body (second three element)
Function Header
Name and type:
• The function type specifies the type of value (like float or double) that the
function is expected to return to the program calling the function.
• If the return type is not explicitly specified, C will assume that it is an
integer type.
• If the function is not returning anything, then we need to specify the return
type as void.
• It is a good programming practice to code explicitly the return type, even
when it is an integer.
• The function name is any valid C identifier and therefore must follow the
same rules of formation as other variable names in C
• The name should be appropriate to the task performed by the function.
Formal parameter list
• The parameter list declares the variables that will receive the data
sent by the calling program.
• They serve as input data to the function to carry out the specified
task.
• Since they represent the actual input values, they are often referred
to as formal parameters.
• The parameters are also known as arguments.
Function Body
• The function body contains the declarations and statements
necessary for performing the required task.
• The body enclosed in braces, contains three parts, in the order given
below:

• 1. Local declarations that specify the variables needed by the function.


• 2. Function statements that perform the task of the function.
• 3. A return statement that returns the value evaluated by the function.
• If a function does not return any value, we can omit the return statement.
• However, note that its return type should be specified as void. Again, it is nice to have a return
statement even for void functions.
• As pointed out earlier, a function may or may not send back any value
to the calling function. If it does, it is done through the return
statement.
FUNCTION CALLS
• A function can be called by simply using the function name followed by a list of
actual parameters (or arguments), if any, enclosed in parentheses.
FUNCTION DECLARATION
• Like variables, all functions in a C program must be declared, before
they are invoked. A function declaration (also known as function
prototype) consists of four parts.
• Function type (return type).
• Function name.
• Parameter list.
• Terminating semicolon.
• A prototype declaration may be placed in two places in a program.
1. Above all the functions (including main).
2. Inside a function definition.

• When we place the declaration above all the functions (in the global
declaration section), the prototype is referred to as a global prototype.
Such declarations are available for all the functions in the program.

• When we place it in a function definition (in the local declaration section),


the prototype is called a local prototype. Such declarations are primarily
used by the functions containing them.
• Prototype declarations are not essential.

• It is not needed, but not using prototypes is bad practice. The


compiler can use prototypes to make sure you're calling the function
appropriately.
CATEGORY OF FUNCTIONS
• A function, depending on whether arguments are present or not and
whether a value is returned or not, may belong to one of the
following categories:

• Category 1: Functions with no arguments and no return values.


• Category 2: Functions with arguments and no return values.
• Category 3: Functions with arguments and one return value.
• Category 4: Functions with no arguments but return a value.
• Category 5: Functions that return multiple values.
NO ARGUMENTS AND NO RETURN VALUES
• When a function has no arguments, it does not receive any data from the calling
function.
• Similarly, when it does not return a value, the calling function does not receive
any data from the called function.
//No Return Without Argument Function in C #include<stdio.h>
/*
[Link] Declaration //Function Declaration
[Link] Definition void add();
[Link] Calling
int main()
*/ {
//Function Calling
add();
return 0;
}
//Function Definition
void add()
{
int a,b,c;
printf("\nEnter The Value of A & B :");
scanf("%d%d",&a,&b);
c=a+b;
printf("\nTotal : %d",c);
}
ARGUMENTS BUT NO RETURN VALUES
• We could make the calling function to read data from the terminal and pass it on
to the called function.
• This approach seems to be wiser because the calling function can check for the
validity of data, if necessary, before it is handed over to the called function
• The actual and formal arguments should
match in number, type, and order.

• The values of actual arguments are


assigned to the formal arguments on a
one to one basis, starting with the first
argument
• We should ensure that the function call has matching arguments.
• In case, the actual arguments are more than the formal arguments (m > n),
the extra actual arguments are discarded.
• if the actual arguments are less than the formal arguments, the
unmatched formal arguments are initialized to some garbage values.
• Any mismatch in data type may also result in passing of garbage values.
Remember, no error message will be generated.
• when a function call is made, only a copy of the values of actual arguments
is
• passed into the called function. What occurs inside the function will have
no effect on the variables used in the actual argument list.
ARGUMENTS WITH RETURN VALUES
• A self-contained and independent function should behave like a ‘black box’ that
receives a predefined form of input and outputs a desired value.
• Such functions will have two-way data communication.
NO ARGUMENTS BUT RETURNS A VALUE
FUNCTIONS THAT RETURN MULTIPLE VALUES
• Up till now, we have illustrated functions that return just one value
using a return statement.
• That is because, a return statement can return only one value.
• Suppose, however, that we want to get more information from a
function. We can achieve this in C using the arguments not only to
receive information but also to send back information to the calling
function.
• The arguments that are used to “send out” information are called
output parameters.
• The mechanism of sending back information through arguments is achieved using
what are known as the address operator (&) and indirection operator (*).
• The actual arguments x and y are input arguments, s and d are output
arguments.
• The first one adds the values a and b and the result is stored in the
memory location pointed to by sum.
NESTING OF FUNCTIONS
Calculate the following Ratio

𝑎
𝑏−𝑐
RECURSION
• A function that calls itself is known as a recursive function.
• The recursion continues until some condition is met to prevent it.
• To prevent infinite recursion, if...else statement (or similar approach)
can be used where one branch makes the recursive call, and other
doesn't.
#include <stdio.h>
int sum(int n);

int main() {
int number, result;

printf("Enter a positive integer: ");


scanf("%d", &number);

result = sum(number);

printf("sum = %d", result);


return 0;
}

int sum(int n) {
if (n != 0)
// sum() function calls itself
return n + sum(n-1);
else
return n;
}
PASSING ARRAYS TO FUNCTIONS
Find largest element in Array

In C, the name of the array represents the


address of its first element.

The array in the called function now


refers to the same array stored in the memory.
Other ways
Formal parameters as a pointer −

void myFunction(int *param)


{
...

}
Formal parameters as a sized array

void myFunction(int param[10])
{
...

}
Formal parameters as an unsized array −

void myFunction(int param[])


{
...
}
two-dimensional Arrays
The function given below calculates the average of the
values in a two-dimensional matrix.
Like simple arrays, we can also pass multi-dimensional arrays to functions. The approach is similar to
the one we did with one-dimensional arrays. The rules are simple.

• The function must be called by passing only the array name.


• In the function definition, we must indicate that the array has two-dimensions by
including two sets of brackets.
• The size of the second dimension must be specified.
• The prototype declaration should be similar to the function header.
THE SCOPE, VISIBILITY, AND LIFETIME OF
VARIABLES
• In C not only do all variables have a data type, they also have a storage class. The
following variable storage classes are most relevant to functions:

1. Automatic variables.
2. External variables.
3. Static variables.
4. Register variables.
• The scope of variable determines over what region of the program a variable is actually available
for use (‘active’)
• Longevity refers to the period during which a variable retains a given value during execution of a
program (‘alive’).
• The visibility refers to the accessibility of a variable from the memory.

• The variables may also be broadly categorized, depending on the place of their
declaration, as internal (local) or external (global).

• Internal variables are those which are declared within a particular function,
• while external variables are declared outside of any function.
Automatic variables
• Automatic variables are declared inside a function in which they are
to be utilized.
• They are created when the function is called and destroyed
automatically when the function is exited, hence the name automatic.
• Automatic variables are therefore private (or local) to the function in
which they are declared.
• Because of this property, automatic variables are also referred to as
local or internal variables.
• One important feature of automatic variables is that their value cannot be changed
accidentally by what happens in some other function in the program.
• This assures that we may declare and use the same variable name in different functions in
the same program without causing any confusion to the compiler.
External variables
• Variables that are both alive and active throughout the entire
program are known as external variables.
• They are also known as global variables. Unlike local variables, global
variables can be accessed by any function in the program.
• External variables are declared outside a function.
• The variables number and length are available for use in all
the three functions.
• In case a local variable and a global variable have the same name, the local
variable will have precedence over the global one in the function where it
is declared.
external declaration
• In case of arrays, the definition should include their size as well.
Static variables
• The value of static variables persists until the end of the program.

• A static variable may be either an internal type or an external type


depending on the place of declaration.
• A static variable is initialized only once, when the program is
compiled.
• internal static variables are similar to auto variables, except that they
remain in existence (alive) throughout the remainder of the program.
Therefore, internal static variables can be used to retain values
between function calls.
register variables
• We can tell the compiler that a variable should be kept in one of the machine’s
registers, instead of keeping in the memory (where normal variables are stored).
• Since a register access is much faster than a memory access, keeping the
frequently accessed variables (e.g., loop control variables) in the register will lead
to faster execution of programs.
Scope and Lifetime of Variables
Nested Blocks
• A set of statements enclosed in a set of braces is known a block or a
compound statement.
• When this program is executed, the value c will be 10, not 30
• The statement b = a; assigns a value of 20 to b and not zero.
• Although the scope of a extends up to the end of main it is not
“visible” inside the inner block where the variable a has been
declared again.
MULTIFILE PROGRAMS
Reference
• Programming in ANSI C by E. Balagurusamy
• C, How to Program by Harvey Deitel and Paul
• C, The Complete Reference by Herbert Schildt
• Let Us C, Yashavant P. Kanetkar

You might also like