Unit 5Functions
Follows IGNOU MCS-201, Unit 5
A large program written as one long main function is hard to read, test and change. Functions solve this by splitting a program into small, named pieces, each doing one well-defined job. This unit explains how to define, declare and call functions, how values travel into and out of them, where variables live and for how long, and how a function can solve a problem by calling itself.
In this unit you will learn to
- Explain why functions are needed, and define and call your own functions.
- Write function declarations (prototypes) and understand what the compiler checks with them.
- Return values from functions with the
returnstatement. - Distinguish scope from lifetime, and use the
auto,extern,staticandregisterstorage classes. - Classify functions by whether they take arguments and return a value.
- Explain call by value and why a function cannot change the caller’s variables directly.
- Write and trace recursive functions with a correct terminating condition.
Sections in this unit
- 5.1Defining and Calling FunctionsUnderstand why functions are used, the parts of a function definition, and how control passes to a function and back when it is called.11 min
- 5.2Function Declarations and PrototypesDeclare functions with prototypes so the compiler can check each call, and understand where prototypes are placed.11 min
- 5.3The return StatementSend a value back from a function with return, use void for functions that return nothing, and understand return types and multiple returns.10 min
- 5.4Scope, Lifetime and the auto and extern Storage ClassesDistinguish scope from lifetime, and understand local (automatic) and global (external) variables and how they are declared.10 min
- 5.5Static and Register VariablesUse static local variables to keep a value between function calls, and understand the purpose and limits of the register storage class.10 min
- 5.6Categories of Functions: Arguments and Return ValuesClassify functions into four categories by whether they take arguments and return a value, and distinguish actual from formal arguments.7 min
- 5.7Call by ValueUnderstand that C passes copies of arguments to functions, trace the classic swap example, and see why the caller's variables are unchanged.9 min
- 5.8RecursionWrite recursive functions with a base case and a recursive case, trace their calls and returns, and compare recursion with iteration.14 min