Chapter Summary
This chapter introduces functions as the fundamental building blocks of C programs. Functions enable programmers to encapsulate logic into independent, reusable modules that reduce code duplication and improve program maintainability.
Key Concepts
-
Functions and Code Organization
- Functions encapsulate logic, promote code reuse, isolate errors, and improve readability
- Function prototypes consist of a function name, parameters, and a return type
returnType functionName(paramType1, paramType2, ...); - Functions must be declared before they are used, either through prototypes or by defining them earlier in the file. It is better to use prototypes to declare functions to ensure that main is not buried inside a long file.
- Functions are defined using
returnType functionName(paramType1 param1, ...) { ... } - To use a function we make a function call
functionName(arguments);and capture return values as needed - Functions receive data through parameters and return results to the calling function
-
Runtime Stack and Execution
- Stack Frames: Each function call creates a stack frame that tracks local variables and parameters
- Stack Operations: Stack frames are added when functions are called and removed when they return
- Variable Scope: Variables in different functions are independent; variables with the same name in different functions are distinct
- Return Values: When a function returns, its stack frame is removed and the return value replaces the function call
-
Function Design Principles
- Cohesion: Functions should perform a single, well-defined task; all code within the function should work toward that objective
- Coupling: Functions should be loosely coupled, meaning they are independent and changes to one function minimally affect others
-
Multi-File Programs
- Header Files (.h): Contain function prototypes and are included by other files
- Source Files (.c): Contain function definitions and include their corresponding header files
- Compilation: Multiple source files are compiled together using
gcc source1.c source2.c ... - Include Syntax: Use
#include "filename.h"for user-defined headers and#include <filename.h>for system headers