C Language

Function in C

In C Language by Baqir Ali

We have seen that C supports the use of predefined library functions which are used to carry out a large number of commonly occurring tasks. A function is a self-contained program segment that carries out some specific, well-defined task. Every C program consists of one or more functions.

  • Note that if a program contains multiple functions then their definitions may appear in any order. The same function can be accessed from several different places within a program.

Why we use function?

  • Less Coding
  • Readability
  • Easy Debugging
  • In Modular programming approach One Module (function) can be developed at a time, so a program can be developed in stages and different programmers can develop different modules separately.
  • Two important advantages of using Functions are reuse and abstraction.
    • We only have to write the procedure one time. Each call to function uses the same code that we have written for the procedure. Because we are reusing this code, our program will be shorter and easier to read.
  • Using Functions also allows us to incorporate abstraction into our programs. Abstraction is a way of simplifying the details of a program. When we think of a program abstractly, we only consider its functionality rather than the details of how it is implemented. One way to think about subprograms (functions) abstractly is to imagine them as black boxes that take a certain input, do some operations on it, and return some output.

How does a function work?

When a function is invoked, program control is transferred to the function. Once the function has carried out its intended action, control is returned to the point from which the function was accessed. Generally speaking, a function processes information passed to it from the calling portion of the program, and returns a single value. Some functions, however, accept information but do not return anything.

How Function works?
How Function works?

Example 1:

 #include <stdio.h> 
 int add(int a, int b)
    int sum;
    sum = a + b;
    return sum;
 void main (void)
    int x = 4, y = 20,  z;
    z =  add (x , y);
    printf ( “ %d \n ”,  z);

Note: A function has three programming elements

  1. Function Prototype
  2. Function Definition
  3. Function Call

Get The Coding Examples From C Language Code Example Page