Header Ads

Functions in C


Definition:

A function in C language is a block of code that performs a specific task. It has a name and is reusable i.e. it can be executed from as many different parts in a C Program as required.


  • Every function has a unique name. This name is used to call function from “main()” or any other function that you write yourself.
  • A function is independent and it can perform its task without intervention from or interfering with other parts of the program.
  • A function performs a specific task. A task is a distinct job that your program must perform as part of its overall operation, such as adding two or more integers, sorting an array into numerical order, or calculating cube of a number, etc.
  • A function returns a value to the calling program/function. This is optional and depends upon the task your function is going to accomplish. Suppose you just want to print some lines through the function then it is not necessary to return a value. But if you are calculating area of rectangle, for instance, and wanted to use the result somewhere in the program, then you have to send back (return) the value to the calling function.


Sometimes when we need to write a particular block of code for more than once in our program, this may lead to bugs and irritation for the programmer. C language provides an approach in which you need to declare and define a group of statements once and that can be called and used whenever required. This saves both time and space.

C functions classified into two categories.

1. Pre-defined Library functions

2. User defined functions



Library functions:

Are those functions which are defined by C library. Example printf(),scanf() and etc.

You just need to include appropriate header files to use these functions. These are already declared and defined in C libraries.

User-defined functions :Are those functions which are defined by the user at the time of writing program. Functions are made for code reusability and for saving time and space.

Parts of a function:


Argument:A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters.

Function Name:This is the actual name of the function. The function name and the parameter list together constitute the function signature.
Return Type:A function may return a value. The return type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return type is the keyword void.


No comments