Functions

 

Functions

A function is a self contained block of code that does some specific task. A function definition has a header and body.

Header

A header of a function is made up of

  • Return type: It is the data type of the value being returned by the function. If a function has no value to return. It has the return type as void.
  • Name : It is the name of the function by which you call it. The name of a function is its address.
  • Argument List : A function can have zero or more parameters known as formal parameters, separated by commas in case it is more than one in number. These formal parameters take values form the calling body so that it can perform the specific tasks on it. These arguments are enclosed within the pair of parenthesis.

Body

Body of a function contains the actual logic to perform certain task. It may return a value of a particular type, if its return type is not defined as void. The body of a function should be enclosed within a pair of curly braces.

Syntax

type name(argument_list)
{
   body
}

 Example : To write a program to get the largest of three values

#include&ltstdio.h&gt
float larger(float x, float y) 
{ 
   return x>y?x:y; 
 } 
void main() 
{
 float a,b,c; 
  printf("Enter Three Numbers"); 
  scanf("%f%f%f",&a,&b,&c); 
  printf(The Largest of %f ,%f and %f is %f",a,b,c,larger(a,larger(b,c))); }

Properties of functions

  • Functions perform well defined task and can be used anywhere in a program
  • Re-usability – A function is created once and can be used any number of times.
  • Information hiding- Function contents are not available in the other part of the program where it is implemented.
  • Extensibility – Functions are written to and called to get more functionality in the other program.
  • Clarity – A function body is written once and saved in one part of the program and called in the other. which removes the extra cluttering from the program and increases the clarity in the codes.
  • Maintainability – A function when used at several places can be modified without affecting the rest of the program and vice versa. Which makes the maintainability more efficient.
  • Testing and debugging – Testing a program in bits and pieces is quite easy. So if you use multiple functions in your program then testing and debugging it individually would be quite easy to test and debug the errors.

What makes a good function?

A good building block is one that has a single, well-defined task to perform. When a program is considered as difficult to manage, it’s often because it has not been designed well and broken up into functions cleanly. To place a piece of code in a function is done for the following reasons :

  • That piece of code is needed in the main program many times. So, by placing it inside a function, it can be written just once, and the places where it was needed can be replaced with just the calls to the new function.
  • The main program is getting too big, so it could be made ( presumably) smaller and more manageable by chopping part of it off and making it a function.

The above two are strong reasons to proclaim a good function but not sufficient. A good function has at least 2 additional properties:

  • It should do just one well-defined task, and should do it well.
  • It should have a clean and narrow interface to the rest of the program.

Function Prototypes

Before using a function in c, compiler need to know details about the function. So the syntax used to declare a function is called function prototype. The function prototype tells the compiler that –

  • The number of arguments being passed to the function
  • The type of each argument being passed to the function
  • Return type of the function

Syntax

return_type function_name(type of each argument)
int larger(int a, int b );

Here larger is the name of function with return type int. It has two integer arguments a and b. both arguments a and b here are optional. So you can also write this as –

int larger(int, int);

Types of Functions

1)  Library Functions 

which are defined in the c libraries and also called pre-defined functions. example – scanf(), printf().

2)  User defined Functions 

In the larger program, it becomes extremely important to break program into more manageable pieces called functions. These functions are declared and defined by the programmer in the program.

How to defined a function?

A Function can be defined by two different styles-

1)  Function Declaration- Declaring a function means to write the function prototype above main() or inside the main but before using it. And defining its body just after the curly braces of main().

Syntax

#include&ltstdio.h&gt
 int sum(int,int); 
void main() 
{ 
int x=5, y=6; 
sum(x,y);
 }
 int sum(int a, int b) 
{ 
int total;
 total=a+b; 
  printf("The Sum of %d and %d = %d",a,b,total); 
  return 0;
  } 

2) Define – A function can be defined without declaring it before main (). These functions must be defined in such a order that

  • The function, that does not call any other function, must be defined first.
  • The function, which may call the first function but not other functions, must be defined second.
  • The function , which may call the first or second functions (or both), must be defined third.
  • That is , the functions are defined in the order that ensures that they are not used in any calling environment before being known to the compiler.

What is the difference between actual parameters and formal parameters?

When the block that calls the function with arguments/parameters and these values are copied into the corresponding arguments of the called function are called actual parameters. The arguments of a function, in which the values of the actual parameters sent by the calling environment are copied, are known as formal parameters. For example, in the following piece of code

#include&ltstdio.h&gt
float larger (float x, float y)
{
if(x>y) return x;
else return y;
}
void main()
{    
int a=5, b=6;
   
printf(“Larger one is %f” ,larger(a,b)) ;

}

Here a and b are actual arguments whose values are sent to the function larger( ) . The values of a and b are copied to the corresponding arguments of larger() , i.e. value of a is copied to x, and value of b is copied to y. Thus, x and y  are formal parameters in the function larger()

Passing arguments to a function

Functions are called by passing their arguments from the calling environment (known as actual parameters) and  the function grasps these arguments in the corresponding parameters (known as formal  parameters) for its parameter list.

There are two methods of passing arguments to a function :

  • Call by value: the values of the actual parameters are passed to the function
  • Call by reference: the addresses of the actual parameters are passed to the function

Call by value

In this method of passing arguments, all the actual  parameters are passed “call-by-value “. That is , each actual parameter is evaluated, and its value is copied to the corresponding formal parameter of the function.

Example:

#include&ltstdio.h&gt
Void change (int n)
{
      n=n+10;
     printf (“Inside change (), the value of m (copied to n) is changed to %d\n”, n) ;
}
void main ( )
{
            int m=5
            printf (“Before change () , value of m=%d\n” ,m) ;
            change() ; /* calling change from the calling environment of main () */
            printf (“but after change (), value of m = %d\n” , m);
}

Output :

Before change( ) , value of m =5

Inside change( ) , the value of m (copied to n) is changed to 15

But after change( ), value of m =15

Call by Reference

The address (or references), and not values, of the actual parameters are passed to the corresponding formal parameters of a function in the call by reference. Thus, inside the function , any change in the value of the variable will be done  by using the address of that variable. This means, inside the function, any change in the  value of the variable, will also be reflected in the calling environment because the value is being changed (inside the function) by using to the address of the variable. By accessing the address of the variable, and changing the value at that address, will physically change the value out there and so will be reflected in the calling environment.

The type of a pointer is same as the type of the variable whose address the pointer stores in it. A pointer is declared and then it is initialized to the address of the variable it points to. It is shown below :

            Int x=5;                        /*declare an integer variable initialized to 5 */

            Int *px=&x;      /* px is a pointer to x, i.e. it stores address of x (&x) */

            *px=10:           /* now, the value at address stored in px changes from 5 to 10 */

Pointers are variables to store addresses. So, to send the address of a variable to a function, we must declare the corresponding formal parameter of the function as a pointer. Now, to show how arguments are passed by reference to a function, we have the following program coming :

#include&ltstdio.h&gt
void change(int *px)                          
{
    *px=*px+5;         /* value at address stored in px is Changed (incremented) */
}
void main( )
{
    int x=5;
    printf (“Before calling change () , value of x = %d\n” ,x) ;
    change(&x) ;                          /* address of x, i.e. &x, is sent to change ( ) */
   printf(“After calling change (), value of x =%d\n” , x) ;
}

Output :

Before calling change ( ) , value of x =5

After calling change ( ), value of x =10

Do C functions really support pass by reference?

No! C functions only support pass by value. That is, the copy of the data is passed to the corresponding formal parameters of the function that is to be called. Pass by reference is also actually passing addresses by value.

What is the difference between “pass by value” and “pass by reference”?

There are following differences between a “pass by value” and “pass by reference”:

  • “pass by value” means copying the values of actual parameters to the corresponding formal  parameters of the called function. “pass by reference” means copying the addresses of actual parameters to the corresponding formal parameters of the called function.
  • When a variable from the calling environment is “passed by value” to the called function then any change in the passed value inside the called function does not affect the value of the variable in the calling environment in any way. But, when a variable is from the calling environment is “passed by reference” to the called function, then any change in the passed value inside the called function is reflected to the value of the variable in the calling environment in any way

Difference between a void and a non-void function

  • Void function does not return any value, a non-void function does.
  • Void function cannot be used in an expression, a non-void function does.
  • Nesting of function calls is possible with non-void functions, but not with void functions.

   Ex : int larger (int, int) ;

result=larger (a, larger (a, larger(c,d) ) ) ; /* nested calls to larger ( ) */

  • The value returned by non-void functions may or may not be utilized; void function does not return any vlaue.
  • Since non-void functions return values, their accidental misuse is possible, but this is not the case with void functions, as they do not return any value.
  • If the value returned by a non-void function is not assigned to a variable, or not printed using printf ( ), then that return value is simply discarded. This is not the case with a void function, as it does not return any value.

Write a function to find all prime numbers between 1 and n (limit) and call it.

Logic: Any number i is prime, if it is not divisible by any j, where j= 2 to  .

 

#include&ltstdio.h&gt                             
#include&ltmath.h&gt                             
void prime(int limit)
{
   Int i, j , s;
   For (i=2 ; i <=n; i++)
   If ( i%j == 0 )  break;                         /* i is not prime; it is divisible by
                                                                  Any of the j */
      If (j>s) printf (“%d “,i) ;                     /* i.e. , if i is not divisible by any j,
                                                               It is prime */
}
}
main ( )
{
   Int n;
   printf(“To find all the prime numbers between 1 and n “) ;
   scanf(“%d”,&n) ;
    prime(n);
}

What value is returned by the main( ) function?

main( ) implicitly returns 0. That is, if there is no explicit return statement with some return value (e.g., return 0;) just before the ending brace of main ( ), then the control returns 0 to the operating system when it encounters the ending brace of the main ( ) . The operating system usually treats return 0; as successful termination of the program.
 

What is the difference between main ( ) and other functions?

main( ) is different from other functions in that it is the only function :
That is declare (and provided) by the C compiler but defined by the programmer.
From which the control starts executing the program.
With restricted number of arguments in the argument list (minimum 0 and maximum 3).
That can be declared with either zero, two or three arguments. This is shown below :
main ( ) /* main ( ) with no arguments */
          {
             . . .
          }
main (int argc, char *argv [ ] )  /* main ( ) with two arguments */
        {
             . . .
        }
Main (int argc, char *argv [ ] , char *env [ ] ) /* main ( ) with three arguments */
         {
               . . .
         }
This much of flexibility is possible only with main ( ) , because it is a function declared implicitly by the compiler in a special manner. For other functions, the number of arguments must match exactly between call and definition.
 

What storage class specifiers can be applied to functions?

There may be only two storage classes that can be applied to functions :
Static
Extern
Out of these, extern is default for functions. That is , all the functions (if not explicitly specified as static) have, by default, extern storage class. So, extern keyword is optional with the functions. Therefore, the following  two declarations are the same:
extern long factorial (int) ;
long factorial (int);
So, we can say that static is the only allowable storage class specifier for a function declaration. Using keyword static before any function declaration makes it accessible only to the file in which it is declared, and not to the other files that are the part of the complete program.

Hope this detailed information about functions would enhance your knowledge about C Programming Language. Please Comment share and like this post.

Similar Posts:

Arrays in C                                  Control Structures in C                         Input/Output functions in C

You may also like these posts :

Reverse Charge Mechanism in Tally.ERP9                                  Let us Learn JavaScript from Step By Step

To Download Official TurboC Compiler from here

To Learn Blogging  and Digital Marketing from my Mentor Deepak Kanakraju through Intership ProgramPl visit digitaldeepak.com  

What value is returned by the main( ) function?

main( ) implicitly returns 0. That is, if there is no explicit return statement with some return value (e.g., return 0;) just before the ending brace of main ( ), then the control returns 0 to the operating system when it encounters the ending brace of the main ( ) . The operating system usually treats return 0; as successful termination of the program.

What is the difference between main ( ) and other functions?

main( ) is different from other functions in that it is the only function :
That is declare (and provided) by the C compiler but defined by the programmer.
From which the control starts executing the program.
With restricted number of arguments in the argument list (minimum 0 and maximum 3).
That can be declared with either zero, two or three arguments. This is shown below :
main ( ) /* main ( ) with no arguments */
          {
             . . .
          }
main (int argc, char *argv [ ] )  /* main ( ) with two arguments */
        {
             . . .
        }
Main (int argc, char *argv [ ] , char *env [ ] ) /* main ( ) with three arguments */
         {
               . . .
         }
This much of flexibility is possible only with main ( ) , because it is a function declared implicitly by the compiler in a special manner. For other functions, the number of arguments must match exactly between call and definition.

What storage class specifiers can be applied to functions?

There may be only two storage classes that can be applied to functions :
Static
Extern
Out of these, extern is default for functions. That is , all the functions (if not explicitly specified as static) have, by default, extern storage class. So, extern keyword is optional with the functions. Therefore, the following  two declarations are the same:
extern long factorial (int) ;
long factorial (int);
So, we can say that static is the only allowable storage class specifier for a function declaration. Using keyword static before any function declaration makes it accessible only to the file in which it is declared, and not to the other files that are the part of the complete program.

0 0 votes
Article Rating
Subscribe
Notify of
guest

3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
trackback
3 years ago

[…] Functions          Control Structures in C                    Arrays in C […]

trackback
3 years ago

[…] in C Language                          Functions                            Arrays in […]

trackback
3 years ago

[…] Functions […]

Please Subscribe to Stay Connected

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

DigitalSanjiv will use the information you provide on this form to be in touch with you and to provide updates and marketing.
Share via
Copy link
Powered by Social Snap