Function def


Programming in C

Functions
 

Function

         A function is a block of code that performs a specific task. It is a self-contained unit of a program that can be called whenever required.

Advantages of Functions

  1. Code Reusability: A function can be called multiple times without rewriting the code.
  2. Modularity: A large program can be divided into smaller modules.
  3. Easy Debugging: Errors can be identified and corrected easily.
  4. Code Readability: Programs become easier to understand.
  5. Code Maintenance: Changes can be made in one function without affecting the entire program.
  6. Reduces Code Duplication: The same logic need not be written repeatedly.

 

Types of Functions in C

C supports two major categories of functions.

1.   Library Functions (Predefined functions) - Library functions are predefined functions provided by the C standard library. We can use these functions by including the appropriate header files. Example

a.   printf(), scanf() from stdio.h

b.   rand() from stdlib.h

2.   User-Defined Functions (Created by programmers) - User-defined functions are functions created by the programmer to perform specific tasks. Example

a.   fnAdd()

b.   fnDisplay()

c.   fnFactorial()

Components of a Function

A user-defined function generally involves three important components:

  1. Function Declaration (Function Prototype)
  2. Function Definition
  3. Function Call

1. Function Declaration

A function declaration informs the compiler about the function name, return type and parameters before the function is used.

Syntax:

return_type function_name(parameter_list);

2. Function Definition

A function definition contains the actual statements that perform the required operation.

return_type function_name(parameters)

{

    // Statements

    return value;

}

3. Function Call

A function call transfers the program's control to the specified function.

 

 


No comments:

Post a Comment

Don't be a silent reader...
Leave your comments...

Anu