Basics of Functions

C programs that we learnt till now were relatively small, easy and had less logic. So we could easily write entire program. But at times we may need to perform same operation at various different parts of program and logic can be too difficult and "heavy" to understand if written within the main() function. In such instances we use functions.

What is a function?

  • Function is a block in C program that consists a logic or statements that are to be executed.
  • We divide entire program in the form of blocks called "functions" so that we can understand it C program becomes easy to write as well as understand.
  • For example, within the C program we need to find averge of three numbers at different parts of program. Insted of writing the program to find average of three numbers we can simply use function to do that operation

main() is also a function

main() itself is a kind of function. It is the function that is executed first. Other functions are called within the main function.
Note : We can call one function within another function, other than main function.
See the video below to undestand calling of function.

Example of a function:

#include <stdio.h>

void trial(); /*function prototype declaration*/
void main()
trial(); /*calling of function*/
printf("Hope I will learn C soon");

void trial() /*function definition*/
 printf("I want to learn C");

Now here we have defined two functions: main() and trial(). Execution of program will begin with main().

void trial() is second line of the program means that function will not return any value. you can find more about return statement here. void word tell the compiler that function won't return anything.

trial(); written within the main() function is called calling of function. We call the function where we need it to be executed.

A seperate block starting with void () trial is called function definition. Here we tell the complier what the function has to do.

Why should we use function?

One may argue that we can put all the logic in main() function. Why to bother about functions then? But when you will wrtie complex programs it would be difficult ro wite the code in the main() function. Also you may need to wrtie same logic multiple if we dont use functions.
Program written using functions appear more structured. It becomes easier to trace what part of program is doing which function. Also it is easier to trace the error(if any) in the program.

See the following video:

No comments:

Post a Comment