Unit II: Functions and Program Structure
1. Defining and Accessing Functions
Functions are the basic building blocks of a C program, allowing for modularity and code reuse. A function definition specifies the task the function performs.
- Defining Functions: Consists of a return type, a function name, and parameters (if any).
- Accessing Functions: A function is "called" by its name followed by arguments in parentheses.
- Passing Arguments: Data is passed to functions via arguments, and their data types must be specified.
2. Function Prototypes and Returns
Functions must be declared before they are used so the compiler knows how to call them.
- Function Prototypes: These are declarations that tell the compiler about the function's name, return type, and parameters.
- Non-Integer Returns: While many functions return integers, C allows functions to return any valid data type, including floats, doubles, or custom structures.
3. Storage Classes and Scope Rules
Storage classes define the scope (visibility) and lifetime of variables within a C program.
4. Block Structure and Header Files
- Block Structure: C supports nested blocks of code defined by curly braces { }, which helps manage variable scope.
- Scope Rules: These rules determine where a variable is accessible based on its declaration point.
- Header Files: Files ending in .h that contain function prototypes and definitions shared across multiple source files.
5. Recursion in C
Recursion is a technique where a function calls itself to solve smaller instances of the same problem.
Recursion is essential for solving problems that can be naturally divided into sub-problems, such as calculating factorials or traversing tree structures.
6. The C Preprocessor
The C preprocessor is a program that processes the source code before it is passed to the compiler.
- Macros: Used to define constants or short functions that are replaced by the preprocessor.
- Directives: Commands like #include and #define that instruct the preprocessor on how to handle the code.
Exam Tips
- Static variables: Remember that a static variable inside a function is initialized only once and preserves its value between calls.
- Prototypes: Always provide a prototype before main() if the function is defined after main() to avoid compiler warnings.
- Base Case: In recursion, always ensure there is a base case to prevent infinite recursion and stack overflow.
Common Mistakes
- Mismatching argument types between the function call and the function definition.
- Confusing local variable scope with global (external) variable scope.