What are the advantages of using functions in c programming? eg what advantage does putting a maths equation in a function have compared with putting it in the main body of code!
What are the advantages of using functions in c programming? eg what advantage does putting a maths equation in a function have compared with putting it in the main body of code!
For one, if the function is needed multiple times, you save on code size (no repeated code) by using a function. Which would make for easier maintainability of the code.
It is all about suitable abstraction.
Modularity...
Create and test a function once, use it multiple times throughout your code.
Local variables are contained and valid only as needed.
Activity inside the function does not impact code outside the function.
Need to change the calculation? Change it in one place, recompile, and everything is updated.
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. Pretty ridiculous! Where would you even start?
Look at it one way, you are making a simple program that adds two numbers (i.e. c = a + b).
And let's say, you are doing it in multiple places, and for arguments sake lets say you added 1,000 numbers, and your code is now 50,000 lines long.
Now you are running the program and find out that the calculation is off.
The question is now, which one of the 1,000 (c = a + b) did you screw up and where in the 50,000 lines of code is the mistake at? With a function it allows you to change your code at one spot vs multiple spots.
That is one example, but there a numerous other examples.
And FYI - The question sounds a lot like a HW question. If you were in need of a HW question being answered, read your text book first. The answer would have been within the first couple of pages on your chapter about functions.
Last edited by Strahd; 12-01-2011 at 10:49 AM.
One advantage is that you can give a better idea of how your programme works!
My homepage
Advice: Take only as directed - If symptoms persist, please see your debugger
Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"