0% found this document useful (0 votes)
9 views

Notes on Function

Uploaded by

orniupoma99
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Notes on Function

Uploaded by

orniupoma99
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

User-Defined Function in C

A user-defined function is a type of function in C language that is defined by the user


himself to perform some specific task. It provides code reusability and modularity to our
program. User-defined functions are different from built-in functions as their working is
specified by the user and no header file is required for their usage.
How to use User-Defined Functions in C?
To use a user-defined function, we first have to understand the different parts of its syntax.
The user-defined function in C can be divided into three parts:
1. Function Prototype
2. Function Definition
3. Function Call

C Function Prototype

A function prototype is also known as a function declaration which specifies the function’s
name, function parameters, and return type. The function prototype does not contain the
body of the function. It is basically used to inform the compiler about the existence of the
user-defined function which can be used in the later part of the program.
Syntax
return_type function_name (type1 arg1, type2 arg2, ... typeN
argN);

We can also skip the name of the arguments in the function prototype. So,
return_type function_name (type1 , type2 , ... typeN);

C Function Definition
Once the function has been called, the function definition contains the actual statements
that will be executed. All the statements of the function definition are enclosed within {
} braces.
Syntax
return_type function_name (type1 arg1, type2 arg2 .... typeN
argN) {

// actual statements to be executed


// return value if any
}

Note: If the function call is present after the function definition, we can skip the function
prototype part and directly define the function.
C Function Call
In order to transfer control to a user-defined function, we need to call it. Functions are called
using their names followed by round brackets. Their arguments are passed inside the
brackets.
Syntax
function_name(arg1, arg2, ... argN);

Example of User-Defined Function


The following C program illustrates how to use user-defined functions in our program.
// C Program to illustrate the use of user-defined function
#include <stdio.h>

// Function prototype
int sum(int, int);

// Function definition
int sum(int x, int y)
{
int sum;
sum = x + y;
return x + y;
}

// Driver code
int main()
{
int x = 10, y = 11;

// Function call
int result = sum(x, y);
printf("Sum of %d and %d = %d ", x, y, result);

return 0;
}
Output
Sum of 10 and 11 = 21
Components of Function Definition
There are three components of the function definition:
1. Function Parameters
2. Function Body
3. Return Value

1. Function Parameters

Function parameters (also known as arguments) are the values that are passed to the called
function by the caller. We can pass none or any number of function parameters to the
function.
We have to define the function name and its type in the function definition and we can only
pass the same number and type of parameters in the function call.
Example
int foo (int a, int b);

2. Function Body
The function body is the set of statements that are enclosed within { } braces. They are the
statements that are executed when the function is called.
Example
int foo (int a, int b) {
int sum = a + b;
return sum;
}

Here, the statements between { and } is function body.

3. Return Value
The return value is the value returned by the function to its caller. A function can only return
a single value and it is optional. If no value is to be returned, the return type is defined as
void.
The return keyword is used to return the value from a function.
Syntax
return (expression);

Example
int foo (int a, int b) {
return a + b;
}

A function definition in C programming 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.
• Argument List − An argument (also called parameter) is like a placeholder. When a
function is invoked, you pass a value as a parameter. This value is referred to as the
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 defines
what the function does.

Passing Parameters to User-Defined Functions


We can pass parameters to a function in C using two methods:
1. Call by Value
2. Call by Reference

1. Call by value

In call by value, a copy of the value is passed to the function and changes that are made to
the function are not reflected back to the values. Actual and formal arguments are created
in different memory locations.
Example
// C program to show use of
// call by value
#include <stdio.h>

void swap(int a, int b)


{
int temp = a;
a = b;
b = temp;
}

// Driver code
int main()
{
int x = 10, y = 20;
printf("Values of x and y before swap are: %d, %d\n", x,
y);
swap(x, y);
printf("Values of x and y after swap are: %d, %d", x,
y);
return 0;
}
Output
Values of x and y before swap are: 10, 20
Values of x and y after swap are: 10, 20
Note: Values aren’t changed in the call by value since they aren’t passed by reference.
2. Call by Reference
In a call by Reference, the address of the argument is passed to the function, and changes
that are made to the function are reflected back to the values. We use the pointers of the
required type to receive the address in the function.
Example
// C program to implement
// Call by Reference
#include <stdio.h>

void swap(int* a, int* b)


{
int temp = *a;
*a = *b;
*b = temp;
}

// Driver code
int main()
{
int x = 10, y = 20;
printf("Values of x and y before swap are: %d, %d\n", x,
y);
swap(&x, &y);
printf("Values of x and y after swap are: %d, %d", x,
y);
return 0;
}
Output
Values of x and y before swap are: 10, 20
Values of x and y after swap are: 20, 10
Advantages of User-Defined Functions
The advantages of using functions in the program are as follows:
• One can avoid duplication of code in the programs by using functions. Code can be
written more quickly and be more readable as a result.
• Code can be divided and conquered using functions. This process is known as Divide
and Conquer. It is difficult to write large amounts of code within the main function,
as well as testing and debugging. Our one task can be divided into several smaller
sub-tasks by using functions, thus reducing the overall complexity.
• For example, when using pow, sqrt, etc. in C without knowing how it is implemented,
one can hide implementation details with functions.
• With little to no modifications, functions developed in one program can be used in
another, reducing the development time.
Difference Between Call by Value and Call by Reference in C
Functions can be invoked in two ways: Call by Value or Call by Reference. These two ways
are generally differentiated by the type of values passed to them as parameters.
The parameters passed to the function are called actual parameters whereas the
parameters received by the function are called formal parameters.
Call By Value in C
In call by value method of parameter passing, the values of actual parameters are copied to
the function’s formal parameters.
• There are two copies of parameters stored in different memory locations.
• One is the original copy and the other is the function copy.
• Any changes made inside functions are not reflected in the actual parameters of the
caller.
Example of Call by Value
The following example demonstrates the call-by-value method of parameter passing C
// C program to illustrate call by value
#include <stdio.h>

// Function Prototype
void swapx(int x, int y);

// Main function
int main()
{
int a = 10, b = 20;

// Pass by Values
swapx(a, b); // Actual Parameters

printf("In the Caller:\na = %d b = %d\n", a, b);

return 0;
}

// Swap functions that swaps


// two values
void swapx(int x, int y) // Formal Parameters
{
int t;

t = x;
x = y;
y = t;

printf("Inside Function:\nx = %d y = %d\n", x, y);


}

Output
Inside Function:
x = 20 y = 10
In the Caller:
a = 10 b = 20
Thus actual values of a and b remain unchanged even after exchanging the values of x and y
in the function.
Call by Reference in C
In call by reference method of parameter passing, the address of the actual parameters is
passed to the function as the formal parameters. In C, we use pointers to achieve call-by-
reference.
• Both the actual and formal parameters refer to the same locations.
• Any changes made inside the function are actually reflected in the actual parameters
of the caller.
Example of Call by Reference
The following C program is an example of a call-by-reference method. C
// C program to illustrate Call by Reference
#include <stdio.h>
// Function Prototype
void swapx(int*, int*);

// Main function
int main()
{
int a = 10, b = 20;

// Pass reference
swapx(&a, &b); // Actual Parameters

printf("Inside the Caller:\na = %d b = %d\n", a, b);

return 0;
}

// Function to swap two variables


// by references
void swapx(int* x, int* y) // Formal Parameters
{
int t;

t = *x;
*x = *y;
*y = t;

printf("Inside the Function:\nx = %d y = %d\n", *x, *y);


}

Output
Inside the Function:
x = 20 y = 10
Inside the Caller:
a = 20 b = 10
Thus actual values of a and b get changed after exchanging values of x and y.
Difference between the Call by Value and Call by Reference in C
Understanding the difference between call by value and call by reference is crucial in C
programming. To see how these methods apply to data structures like arrays and linked lists,
the C Programming Course Online with Data Structures provides detailed explanations and
examples.
The following table lists the differences between the call-by-value and call-by-reference
methods of parameter passing.
Call By Value Call By Reference

While calling a function, instead of passing


While calling a function, we pass the
the values of variables, we pass the address
values of variables to it. Such functions
of variables(location of variables) to the
are known as “Call By Values”.
function known as “Call By References.

In this method, the value of each


In this method, the address of actual
variable in the calling function is copied
variables in the calling function is copied into
into corresponding dummy variables of
the dummy variables of the called function.
the called function.

With this method, the changes made to


With this method, using addresses we would
the dummy variables in the called
have access to the actual variables and hence
function have no effect on the values of
we would be able to manipulate them.
actual variables in the calling function.

In call-by-values, we cannot alter the


In call by reference, we can alter the values of
values of actual variables through
variables through function calls.
function calls.

Values of variables are passed by the Pointer variables are necessary to define to
Simple technique. store the address values of variables.

This method is preferred when we have


This method is preferred when we have to
to pass some small values that should
pass a large amount of data to the function.
not change.

Call by value is considered safer as Call by reference is risky as it allows direct


original data is preserved modification in original data

Note In C, we use pointers to achieve call-by-reference. In C++, we can either use pointers or
references for pass-by-reference. In Java, primitive types are passed as values and non-
primitive types are always references.
Conclusion
In conclusion, Call by Value means passing values as copies to the function, so that the
original data is preserved and any changes made inside the function are not reflected in the
original data, whereas Call by Reference means passing references to the memory locations
of variables (in C we pass pointers to achieve call by reference), hence changes made inside
the function are directly modified in the original values. The choice between the two
completely depends on the particular requirements and considerations of a program.

Important Points about main() Function


• A C program must have a main() function.
• The main is not a C keyword.
It is classified as a user-defined function because its body is not pre−decided, it
depends on the processing logic of the program.
By convention, int is the return type of main(). The last statement in the function
body of main() returns 0, to indicate that the function has been successfully
executed. Any non−zero return value indicates failure.
• Some old C compilers let you define main() function with void return type.
• However, this is considered to be non−standard and is not recommended.
• As compared to other functions, the main() function:
o Can't be declared as inline.
o Can't be declared as static.
o Can't have its address taken.
o Can't be called from your program.

How does main() Works in C?


The program's execution starts from the main() function as it is an entry
point of the program, it starts executing the statements written inside it.
Other functions within the source program are defined to perform certain
task. The main function can call any of these functions. When main calls
another function, it passes execution control to the function, optionally
passing the requisite number and type of arguments, so that execution
begins at the first statement in the called function. The called function
returns control to main when a return statement is executed or when the
end of the function is reached. Note that return statement is implicitly
present as the last statement when its return type is int.

A program usually stops executing when it returns from or reaches the


end of main, although it can terminate at other points in the program for
various reasons. For example, you may want to force the termination of
your program when some error condition is detected. To do so, you can
use the exit function.

You might also like