Wednesday, December 15, 2021

Function in C

In this article we will discuss basic topics of C-function as mentioned below
  • Function definition and Declaration
  • Types of functions in C
  • Static function in C
  • Function arguments 
    • By Value
    • By Reference
  • Function return value is 
    • Global variable
    • Local variable
    • Static variable
    • Enum type
  • Passing Arrays to functions
  • Return an array from function
  • Returning more than one value from function
  • Returning a Pointer from a Function
========================================================================================================

Function Definition and Declaration

A function is group of statements that together form a task, or Large program logic divided into smaller logics this smaller logical entity is called as "Function".

Functions are following aspects:

Function Declaration:  A function must be declared globally in a C-Program to tell the compiler about the function name, function parameters and function return type.
Syntax:  <return_type>  <function_Name> (argument list);  i.e.., int Swap(int, int);

Function Definition: It contains the actual statements which to be executed. when the function is called  "Function body executed". Execution part is implemented in function definition. 
Syntax:  <return_type>  <function_Name> (argument list)
{
    Function body;
}
Function call: Function can call anywhere in the program. while calling we should check the number of arguments.
Syntax:  <function_Name> (argument list);

Return Value: A return statement ends the function execution, and returns the control to the calling function.  A C-Function may or may not return value from function. if you don't have any return value then mentioned as void for the return type.




Number of Arguments mismatch error



Types of functions in C

  • according to system, there are two types of functions such as "Library functions" and "User-defined functions".
  • User-defined functions are categorized into four types
    • function without arguments and without return value
    • function without arguments and with return value
    • function with arguments and without return value
    • function with arguments and with return value

Function without arguments and without return value

This type of functions, function does not receive any input arguments and does not return any value. 


Function without arguments and with return value

In this type of functions, function does not receive any arguments from calling function but it returns the values.



Function with arguments and without return value

When a function has arguments, it receive an arguments from the calling function but it does not return any values.

Function with arguments and with return value

In this type of functions, function has arguments and also return value.

Static function in C

Static function is same like a Static variable. its scope is limited to the file where the function is defined. A function can be declared as static function by placing the static keyword before the function name.
These functions are used for hiding the function names from different files. 
  • when you want to define some functions that should not be sharable (callable) in another file.
  • static functions are also helpful to handle declaration conflict issue - if there are two functions in two different files with same name, function declaration will be conflict. We can make them static.
Syntax:

static  <return type>  func_name(arguments)

Example 

File1.c 
static void Display()
{
    printf("I am in File1.c and function Display()");
}

File2.c

#include <stdio.h>

int main()
{
    Display();
return 0;
}

here Scope of the function limited to File1.c file but try to access from File2.c so function visibility is only for File1.c hence we can't access function. 
In the real-time projects, if we need to hide the functions from customer we will create static functions  and made as private function. we will share only public functions with customer. 

Function call by Value vs Function call by Reference

To discuss this topic we need to understand "Actual parameters" and "Formal parameters".

When we call a function, we are passing an arguments to function these are called "Actual parameters".
Where you receive parameters of function are called "formal parameter". 
Explain the concept below.

int Square_Num(int num// Here "num" is formal parameter
{
 return (num*num);
}

int main()
{
    int a=20, res;
    res= Square_Num(a);// Here "a" is actual parameter 
    printf("value is %d\n", res);
    return 0;
}

By definition, Function by value means you are making copy of actual parameters and working on the copied parameters. once the function is returned from called function, activation records of variables in the stack is deleted. hence no effect on the "actual parameters". see below picture for activation records created when the function is called and when function is returned. 




By definition, Function call by Reference means address of actual parameters are passed to formal parameters. formal parameters are working on the addresses of "actual parameters"
This method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.

Function Return value

Function can return the local variable, global variable, static variable, enum, array, array of pointer, structure and structure pointer.
if function not returning any value then called as "void" return type. If a return type isn't specified, the C compiler assumes a default return type of int.

Note: After return statement, None of the C-statements executing.
  • Function return value is local variable: In this method, programmer will declare a variable within the function, programmer will return the local variable to the calling function after the task is performed. function will end by using "return" statement.  
  • Function return value is Global variable: In this method, programmer will declare a global variable, programmer will return the global variable to the calling function. 
  • Function return value is static variable: This method same as local variable return type. it does not make any difference but static variable always initialized with zero. one important thing is this variables can not access outside the file. 
Note: Local return has file scope it means that function can return the value within file but global return has program scope it means that function can return the values in different files or this return value can be used anywhere in the program. from the below program we can not differentiate the usage but if we have more than one source files then we can check the difference. 


Function return value is Enum type

Enumeration (or enum) is a user defined data type in C. It is mainly used to assign names to integral constants, the names make a program easy to read and maintain.
We will apply this method to driver development code. whenever the HW status or program status or peripheral status is required, then programmers will defined as enum. 
  • suppose we have three status such as Success, Pending, Error, we will return this status to function according to the signal value. 
  • we will create  enum type variable and used as function return value.
Look into the program below. 


Passing Arrays to functions

In this section we will discuss following topics
  • Pass Individual Array Elements 
  • Pass Entire array
    • Formal parameter as a pointer. i.e.., int func_calculate(int * argumentName)
    • Formal parameter as a sized array. i.e.., int func_calculate(int  arr[5])
    • Formal parameter as a unsized array. i.e.., int func_calculate(int  arr[])
  • Array of pointer
  • Function pointer array, Structure array, Structure array pointer : These topics are discussed in the structure concepts articles.  Link:  Structure in C
Pass Individual Array Elements
This method is similar to passing variable to the function. 


Passing Arrays as Function Arguments

Method-1: using pointer, Formal parameter as a pointer
Syntax :   <return type> <function_Name>(datatype* argument);
Look into the below program
  • Function definition: void comparator(int* );  function argument is pointer type
  • Function call : comparator(arr);  here "arr" is base address of an array. base address is sent to the function.
  • Function declaration: void comparator(int* x){} here "x" receives the base address of an array and increment the pointer address inside the function and accessed each array elements.


Method-2: Formal parameters as a Sized array
Syntax :   <return type> <function_Name>(datatype argument[Array Size]);
  • Function definition:  void comparator(int[ARRAY_SIZE] ); here array size is mentioned 
  • Function call: comparator(arr); from call-wise no difference. we will send it an array.
  • Function declaration: void comparator(int x[ARRAY_SIZE]) {}; here also formal parameter mentioned with array size.


Method-3: Formal parameters as a Unsized array
Syntax :   <return type> <function_Name>(datatype argument[ ]);
  • Function definition:  void comparator(int[ ] ); here array size is not mentioned 
  • Function call: comparator(arr); from call-wise no difference. we will send it an array.
  • Function declaration: void comparator(int x[ ]) {}; here also formal parameter not contains any array size. 

all three declaration methods produce similar results because each tells the compiler that an integer pointer is going to be received. demonstrated in below program.

Array of pointers

How it is works?
Array of pointers are similar to pointer variable but it hold the addresses of number of variables. Each index assigned with address of different variable.

Look into the below program.
int* ptr;  is the pointer variable. it holds the address of another variable "ptr=&a;"
int* ptr[5]; is the array of pointer. it holds the addresses of five integer variable.
int *ptr[5]={&a, &b, &c, &d, &e};




How to pass array of pointer to functions?

Pointer variable is holds the address of another variable.
Array pointer is holds the addresses of N-Number of  variables. this point discussed above.
As per our declaration, ptr[0] holds the address of variable "a".  so if we need to deference value of "a" then use "*ptr[0]". Since each array index pointing to a variable's address, we need to use "*ptr[index]" to access the value stored at the particular index's address.
pointer Index is again internally represented as pointer hence use double pointer.

arr[0] same as *(arr+0), In general arr[i] same as *(arr+i)
*arr[0] same as *(*(arr+0)), In general *arr[i] same as *(*(arr+i))



Return array from function

function can not return an array from function directly because return statement returns only one value so we can return the address of variable and made return type as "pointer" type.

Method-1: use function argument as pointer or array



Method-2: use static variable
In this method, we will create static array and return the base address of static variable. static variable as file scope so this variable not deleted after the function is returned. 



Method-3: Use global array to store the local array.
This method is simple but stack memory issue because array activation records is present through out the program.
In this method, create one global variable array and copy the local contents to the global. this is not an efficient method. because of stack consumption and array can access anybody in the program. 



Returning more than one value from function

By definition of "return" statement, it returns only one value. if programmer wants to get multiple variable output in his calling function then He/She need to use "call by reference" concept to hold the address of an variable.


Look into above program, In Calculator() function a and b are passed using call by value, whereas sum, sub and mul are passed using call by reference. As a result Calculator() function knows the address of sum, sub and mul variables, so it access these variables indirectly using a pointer and changes their values.

Returning a Pointer from a Function

As we already seen many above program, return type made as pointer and return the address of an variable from called function.
For example, in the following program, the function func_name( ) receives the address of the variable "x". The returned value is then assigned to the pointer variable ‘ptr’ in the calling function.

To confirm above statement we printed addresses of "return variable", pointer variable and address of function. so address of "return variable" and pointer variable is same but function address is different.

address of x in func_name() is 0x7ffc17f54cc8
address of pointer is 0x7ffc17f54cc8
address of func_name() is 0x55d78710e2a1



========================================================================================================
Some of the complex topics will discuss in the upcoming articles.

Thanks for visiting the Post..!!

======================================================================================================== 

No comments:

Post a Comment