0% found this document useful (0 votes)
16 views9 pages

User Defined Function

The document provides an overview of user-defined functions in C programming, detailing their necessity for simplifying complex problems, debugging, and modular programming. It outlines the structure of function definitions, including function headers and bodies, as well as the different types of functions based on arguments and return values. Additionally, it discusses parameter passing methods, local and global variables, and the distinction between actual and formal arguments.

Uploaded by

sahithrsalian33
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)
16 views9 pages

User Defined Function

The document provides an overview of user-defined functions in C programming, detailing their necessity for simplifying complex problems, debugging, and modular programming. It outlines the structure of function definitions, including function headers and bodies, as well as the different types of functions based on arguments and return values. Additionally, it discusses parameter passing methods, local and global variables, and the distinction between actual and formal arguments.

Uploaded by

sahithrsalian33
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/ 9

Programming in C User defined functions

User-DefinedFunctions
C functions can be classified into two categories:

a) library functions : library functions are not required to be written by us. for
example main(), printf(),sqrt() etc
b) user-defined functions. a user-defined function has to be developed by the user
at the time of writing a program. A function is a self-contained block of code
that performs a particular task.

NEED FOR USER-DEFINED FUNCTIONS

● To simplify a complex problem.


● To simplify the task of debugging, testing, and maintaining.
● If a program is divided into functional parts, then each part may be independently
coded and later combined into a single unit.
● It is easy to repeat certain calculations at many points throughout a program using
functions.
● It facilitates top-down modular programming. Here, the high level logic of the
overall problem is solved first while the details of each lower-level function are
addressed later.
● The length of a source program can be reduced.
● It is easy to locate and isolate a faulty function for further investigations.
● A function may be used by many other programs.

A MULTI-FUNCTION PROGRAM
A function is a self-contained block of code that performs a particular task. Once a
function has been designed and packed, the inner details of operation are invisible to the
rest of the program.

● Any function can call any other function.


● It can call itself. (recursion)
● A function can be called more than once.
● The functions can be placed in any order.

ELEMENTS OF USER-DEFINED FUNCTIONS

● Functions are classified as one of the derived data types in C.


● Function name must be a valid identifier.
Elements of functions:
1. Function definition.
2. Function call.
3. Function declaration.

Page 1
Programming in C User defined functions

DEFINITION OF FUNCTIONS

A function definition, also known as function implementation shall include the following
elements;
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, namely,
• function header (First three elements); and
• function body (Second three elements).
A general format of a function definition:
function_typefunction_name(parameter list)
{
local variable declaration;
executable statementl;
executable statement2;
return statement;
}

⮚ Function Header

The function header consists of three parts: the function type (also known as return
type), the function name and the formal parameter list. A semicolon is not used at the end
of the function header.

● The function typespecifies 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 explicitlyspecified, default type will be integer type.
- If the function is not returning anything, then specify as void.
● The function name is any valid C identifier. 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.
- The parameter list contains declaration of variables separated by commas and
surrounded by parentheses.
- Examples: float quadratic (int a, int b, int c) {. . . }
double power (double x, int n) {. . . }

Page 2
Programming in C User defined functions

● The declaration of parameter variables cannot be combined.


That is, int sum (int a,b) is illegal.

● A function that do not receive anyvalues from the calling program, indicatedas
empty parameter list or use void.
Eg: void printline(void)
{
.....
}

⮚ Function Body
● The function body contains the declarations and statements necessary for
performing the required task.
● The body enclosed in braces, contains three parts,:

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 thereturnstatement.

⮚ RETURN VALUES AND THEIR TYPES


● A function mayor may not send back any value to the calling function.
● If it does, it is done through the return statement.

The return statement can take one of the following forms:


return;
or
return(expression);
● The first, the 'plain' return does not return any value; it acts much as the closing
brace ofthe function. When a return is encountered, the control is immediately
passed back to thecalling function.
● Example:
if(error)
return;
● The second form of return with an expression returns the value of the expression.
For example: int mul (int x, int y)
{
int p;
p = x*y;
return(p);
}
returns the value of p which is the product of the values of x and y.

Page 3
Programming in C User defined functions

We can also write it as: return(x*y);

A function may have more than one return statements. This situation arises when the
valuereturned is based on certain conditions. For example:
if( x<= 0 )
return(0);
else
return (1);

⮚ 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.

It is having the following syntax:


Variable=function_name(arg1,arg2,...);
Example:

● When the compiler encounters a function call, the control is transferred to the
functionmul().
● This function is then executed line by line and a value is returned whena return
statement is encountered. This value is assigned to y.

● The function call sends two integer values 10 and 5 to the function.
● int mul(int x, int y)which are assigned to x and y respectively. The function
computes theproduct x and y, assigns the result to the local variable p, and then
returns the value 25 to the main where it is assigned to y again.

Page 4
Programming in C User defined functions

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.

General format:

Function-type function-name (parameter list);

This is very similar to the function header line except the terminating semicolon.

Example:int mul (int m, int n); /* Function prototype */

mul (int a, int b);

When a function does not take any parameters and does not return any value, its
prototype is written as:

void display (void);

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, the prototype is referred to
as a global prototype.
When we place it in a function definition, the prototype is called a local prototype.
Such declarations are primarily used by the functions containing them.

Points to note:

1. The parameter list must be separated by commas.


2. The parameter names do not need to be the same in the prototype declaration and
the function definition.
3. The types must match the types of parameters in the function definition, in number
and order.
4. Use of parameter names in the declaration is optional.
5. If the function has no formal parameters, the list is written as (void).
6. The return type is optional, when the function returns int type data.
7. The retype must be void if no value is returned.
8. When the declared types do not match with the types in the function definition,
compiler will produce an error.

Page 5
Programming in C User defined functions

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:

1: Functions with no arguments and no return values.


2: Functions with arguments and no return values.
3: Functions with arguments and one return value.
4: Functions with no arguments but return a value.
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.
● When it does not return a value, the calling function does not receive any data
from the called function.
● There is no data transfer between the calling function and the called function.

#include<stdio.h>
void printline(void);
main()
{
printline();
}
void printline(void)
{
int i;
for(i=0;i<=30;i++)
printf(“%d”,i);
printf(“\n”);
}
● When there is nothing to be returned, the return statement is optional.
● The closing brace of the function signals the end of execution of the function, thus
returning the control, back to the calling function.

ARGUMENTS BUT NO RETURN VALUES

● In this approach the calling function pass argument to the called function.
● The nature of data communication between the calling function and the called
function with arguments but no return value.

The definitions of the called functions include arguments as follows:

void printline(char ch)


void value(float p, float r, int n)

Page 6
Programming in C User defined functions

Example:
#include<stdio.h>
void printline(char c);
main()
{
printline(‘*’);
}
void printline(char c)
{
int i;
for(i=0;i<10;i++)
printf(“%c”,c);
printf(“\n”);
}

ARGUMENTS WITH RETURN VALUES


● In this approach calling function sends argument to the called function.
● Called function return a value back to the calling function.
● Such functions will have two-way data communication.

Example Program:
#include<stdio.h>
intvalue(int x, int y);
main()
{
int a=10,b=15,sum;
sum=value(a,b);
printf(“\n%d”,sum);
}
int value(intx,int y)
{
return(x+y);
}

NO ARGUMENTS BUT RETURNS A VALUE

● In this approach functions may not take any arguments. Hence no arguments are
passed.
● But it returns a value to the calling function.
Example:
int get_number(void);
main()
{
int m = get_number( );
printf("%d",m);
}
int get_number(void)

Page 7
Programming in C User defined functions

{
int number;
scanf("%d",&number);
return(number);
}

PASS BY VALUE & PASS BY REFERENCE


The technique used to pass data from one function to another is known as parameter
passing. Parameter passing can be done in two ways.
● Pass by value (also known as call by value)
● Pass by Pointers (also known as call by pointers)

In pass by value, values of actual parameters are copied to the variables in the parameter
list of the called function. The called function works on the copy and not on the original
values of the actual parameters. This ensures that the original data in the calling function
cannot be changed accidentally.

Inpass by pointers (also known as pass by address), the memory addresses of the
variables rather than the copies of values are sent to the called function. In this case, the
called function directly works on the data in the calling function and the changed values
are available in the calling function for its use.

#include<stdio.h> #include<stdio.h>
int mul(int x,int y); int mul(int *x,int *y);
main() main()
{ {
int y,a=10,b=5; int y,a=10,b=5;
y=mul(a,b ); /* pass by value */ y=mul(&a,&b); /* pass by reference */
printf(“Product=%d”,y); printf(“Product=%d”,y);
}
} int mul(int *x,int*y)
int mul(int x,int y) {
{ int m= *x , n= *y;
return(x*y); return(m*n);
} }

Local & global Variables:

● Variables declared inside a block or function are said to belong only to that
block and all referred as local variable .
● Value of local variables are available only in that block and outside it.

● Variables declared in the declaration part before the main function block are
called global Variables.

Page 8
Programming in C User defined functions

● The value of global Variable thought the program & in every block of the
program.
Example:
#include<stdio.h>
int x;
main()
{
int a;
}
Here a is a local variable. x is global variable.

Actual and formal Arguments:

● A function may be called in any portion of a program.


● A function Call include the function name with some parameters or Arguments.
● The Arguments in the function call are called actual Arguments.
● They represent values that are passed to the function.

● The Definition of a function includes a set of parameters or arguments .


● These argument are called as formal arguments or dummy arguments.
● Formal arguments get a copy of the values from the actual arguments when the
function is called.

● The number of formal arguments and actual arguments should be same.


● The data types of the formal and actual arguments and the order of creation
should be same.
● Example
#include<stdio.h>
int mul(int x,int y);
main()
{
int y;
y=mul(10,5 ); /* function call – ACTUAL PARAMTER*/
printf(“Product=%d”,y);

}
int mul(int x,int y) /* function definition – FORMAL PARAMTER*/
{
return(x*y);
}
*****************

Page 9

You might also like