C programming Function

0 28

What is Function?

A function is a unit of a program that is designed to do specific task. There are two type of functions:

  1. Built-in Function
  2. User defined function.

Built-in functions such as printf(),putchr(),getchr() etc these do some specific task and created by C language creators.

User defined functions are created by C language users to do our specific task. We need to create our own function so that we don’t write same code over and over. These kind of functions are subroutine, branch of a code and can be called whenever we need it.


Creating Function in C language

It will be better to paste my sample code and explain line by line:

  • in line 9 i first declared the function and the function type. Like variable function also has type. But i declared it as void mean, no-type.
  • Inside the main() function i called the banner() function. Because i want to print ‘—–‘ before doing anything else. And i also want to print ‘—-‘ at the end, so i called the banner() in line 16 too.
  • In line 9 i just let the compiler know that i have declared a function. From line 22 i let the compiler know that here is my branch banner() code start.
  • In line 14 and 24 i used well known builtin function printf() to print something as banner. This can be replaced to putchr() function too.

Also a function can have parameters. For example:

Here i am just providing values to the calling functions. Code inside banner(char chr,int counter) can use the value of chr and counter as much as possible.


Return value with Function

A function itself can return a value. We also can compare the value with other things. If we want to do a simple multiplication , then our first plan would be doing it in a integer variable like int multi=2*2; . But we can do this in separate functions. Here is my sample code:

  • In line 14 i first declared a variable. Then called the function with parameter’s value. Whatever return, This is working as value of the test1 variable.
  • In line 35 the function exist. Line 36 is another integer variable that doing the math. Whatever value the variable has , i am giving this value to the function to hold with statement return test; . So finally, The function rtrn() is equal to 4.


For practices purpose i have tried to explain my code. If you see anything wrong or have any advise or questions , please do comments!

Leave a comment