把功能封装在一个模块内,供用户直接调用,比如cout,cin,time(0),rand()等,这些是函数系统已经做好的,有些功能没有函数现成可以实现的,我们就根据自己的需求进行个性开发。这章我们就是重点讲授如何创作自己的函数。
使用函数的优点
•程序结构清晰,逻辑关系明确,程序可读性强。
•解决相同或相似问题时不用重复编写代码,可通过调用函数来解决,减少代码量。
•利用函数实现模块化编程,各模块功能相对独立,降低调试难度
A function is a set of statements that take inputs, do some specific computation and produces output.
The idea is to put some commonly or repeatedly done task together and make a function so that instead of writing the same code again and again for different inputs, we can call the function.
Why do we need functions?
- Functions help us in reducing code redundancy. If functionality is performed at multiple places in software, then rather than writing the same code, again and again, we create a function and call it everywhere. This also helps in maintenance as we have to change at one place if we make future changes to the functionality.
- Functions make code modular. Consider a big file having many lines of codes. It becomes really simple to read and use the code if the code is divided into functions.
- Functions provide abstraction. For example, we can use library functions without worrying about their internal working.