Functions in C programming



Function definitions

Functions allow you to modularize a program. All variables defined in function definitions are local variables - they can be accessed only in the function in which they’re defined.

Most functions have a list of parameters that provide the means for communicating information between functions. A function’s parameters are also local variables of that function.

Packaging code as a function allows the code to be executed from other locations in a program simply by calling the function.

Creating and using a programmer-defined functions

   
    // Creating and using a programmer-defined function.
    #include <stdio.h>
    int square( int y ); // function prototype
    
    // function main begins program execution
    int main( void )
    {
    int x; // counter
    
    // loop 10 times and calculate and output square of x each time
     for ( x = 1; x <= 10; ++x ) {
      printf( "%d  ", square( x ) ); // function call
     } // end for
      puts( "" );
    } // end main
    
    // square function definition returns the square of its parameter 
    int square( int y ) // y is a copy of the argument to the function
    {                                                                   
    return y * y; // returns the square of y as an int              
    } // end function square    

   Output:
   1  4  9  16  25  36  49  64  81  100

Programmer-defined function maximum

This second example uses a programmer-defined function maximum to determine and return the largest of three integers.

Next, they’re passed to maximum , which determines the largest integer. This value is returned to main by the return statement in maximum .


    // Finding the maximum of three integers.
    #include <stdio.h>
    int maximum( int x, int y, int z ); // function prototype 
    
    // function main begins program execution 
    int main( void )
    {
    int number1; // first integer entered by the user 
    int number2; // second integer entered by the user 
    int number3; // third integer entered by the user 
    printf( "%s", "Enter three integers: " );
    scanf( "%d%d%d", &number1, &number2, &number3 );
    
    // number1, number2 and number3 are arguments 
    // to the maximum function call 
    printf( "Maximum is: %d\n", maximum( number1, number2, number3 ) );
    } // end main 
    
    // Function maximum definition
    // x, y and z are parameters  
    int maximum( int x, int y, int z ) {
    int max = x; // assume x is largest   
    
    if ( y > max ) { // if y is larger than max,
    max = y; // assign y to max   
    }  // end if   
    
    if ( z > max ) { // if z is larger than max,  
      max = z; // assign z to max     
    } // end if        
   return max; // max is largest value   
    } // end function maximum 

    Output:
    Enter three integers: 55 103 77
    Maximum is: 103

Ads Right