Take home message : Functions make your code easier to read and increase the re-usability of your code.
I will use an example from my small experience. Print an array of N size. When I started, I didn't use functions, so every time I had to search for the code in my previous program and copy paste it to the new one. As the programs getting bigger and bigger, that was difficult, enough difficult to make me write the function from scratch. Then, I wrote the code that needs to be written for printing an array in a function, and simple reuse this function every time I need it.
First approach
Code:
...
int main(void)
{
int i;
...
for( i = 0 ; i < 10 ; i++)
printf(...);
return 0;
}
Second approach
Code:
...
void printArray(int* array);
int main(void)
{
...
printArray(array);
return 0;
}
void printArray(int* array)
{
int i;
for( i = 0 ; i < 10 ; i++)
printf(...);
}
But, as I used the function again and again, I saw that I had to change the condition of the for loop again and again, according to the needs of every program. Many times I forgot to, thus got a logical error( less elements were printed ) or I was going out of bounds (segmentation fault). Of course, I spent much time searching for the bug, which was in the function!
So, I decided to make the function a bit more generic. I decided to pass the size of the array, as second parameter of the function and never needed to worry about that again. No errors, no time spent on debugging for the part of program that prints the elements of the array. (!) Re-use of code, through functions usually, makes you write less code from scratch and decreases the amount of code that you have to debug. The re-used code is considered to be correct,
Third approach (I still use this function!)
Code:
..
void printArray(int* array, int N);
int main(void)
{
....
printArray(array, 50);
return 0;
}
void printArray(int* array, int N)
{
int i;
for(i = 0 ; i < N ; i++)
printf(..);
}
You can make the function more generic than this, but I think that for usual use, this is more than fine
After this, I really understood how valuable this function was, so I decided to make other too. After some functions for filling/printing arrays, I decided to make one function for dynamically allocate a 2D array and another one for freeing it. I still use them! You can see the code here if you like.
And just think about functions you already use: imagine if you had to rewrite the entire code for printf() in main() every time you wanted to print some text on the screen.
Source for the quote from an old thread of this forum.