Function in C

On this page, we will learn about type casting, how to use it, types of type casting, implicit type casting, explicit type casting, widening type casting, narrowing type casting, sign conversion type casting, and an example of type casting in C.


What is function in C programming?

Function: Function is is a set of statements that take inputs, do some specific computation and process an Output and either return it from where it is called or print the out. As the compiler read the code line by line so I recommand you to write the function before the main() function. If you witre a function below the main() function then you must have reference of this funtion before the main() funtion.

Declaration:


  return_type function_name() {
    // function body
    // statements

    // return statement (if applicable)
  }

A function is consist of few things these are---

  • Return Type : A function must have a return type . Return type indicates the function can return a value or not. For an example the void type function call do all the computation but it can not return some value.
  • Function Name : This namming rule is same as variable namming rule.
  • Parameters : A function must have () and in between this you take and pass value one to the another function.
  • Body : In the function body you can write the code .

Let's see an example:


  #include<stdio.h>
  int add(int x, int y){
   int sum;
   sum = x + y;
   return sum;
  }  
  int main(){
   int v1= 4, v2= 6;
   int result = add(v1,v2);//function calling
   printf("Output is: %d",result);
  }

Output:

    Output is: 10

1. Call by value:

If we send value as prarameter then it is called call by value . Above code is an example of call by value.



2. Call by reference :

If we send the address of variable as prarameter that is call call by reference .See the following example:

    
  #include<stdio.h>
  int add(int *a, int *b){
    int c;
    c = *a + *b;
    return c;
  }  
  int main() {
    int v1= 4, v2= 6,result;
    result = add(&v1,&v2);//function calling
    printf("Output is: %d",result);
  }

Output:

   Output is: 10