C/Functions
Functions[edit]
In today's world we believe that Time is Money. The less time you spend in writing a program, the more efficient use of resources. Functions help us to avoid duplication of code and hence save time, cost and effort.
Let's say we would like to write a code that calculates the square of a number. The application that we are asked to design requires that you calculate the square of several numbers again and again. So, you will write the following code to calculate the square of the number wherever needed.
int result; result = a * a;
If you have to calculate the square of the number at 3 different places in your program, you will have to write these lines of code over and over again.
void main() { ___________; ___________; result = a * a; ___________; ___________; result = b * b; ___________; ___________; result = c * c; }
Instead of doing this over and over again, we can define a function -
int square(int n) { int ans = n * n; return ans; }
Once a function has been defined, we can now use this function wherever we would like to use it. For example,
void main() { ___________; ___________; result = square(a); ___________; ___________; result = square(b); ___________; ___________; result = square(c); }
Thus, instead of writing the entire code over and over again, we can simply call the function here. Functions become the backbone of any C algorithm. Any C data type can be passed to a function (except an array or function - if passed they will be converted to pointers), and any C data type can be returned (except an array or function). Functions can also call other functions:
int multiply_together( int n1, int n2 ) { return n1 * n2; }
int add_two_and_multiply( int n1, int n2 ) { n1 = add_two( n1 ); return multiply_together( n1, add_two( n2 ) ); /* returns (n1+2)*(n2+2) */ }
You can call a function inside a function, as illustrated above.
Every C program has at least one function, that function being main(), which is the entry point of every program.
Project: C |
Previous: C/Flow Control — C/Functions — Next: Pointers and Arrays |