CSS Computer Science (Optional) — Paper-I, Section-A, Topic II subtopic. How code is organized into reusable, callable units, and how data moves in and out of them.
Why Use Functions
- Modularity: breaks a large program into smaller, manageable pieces
- Reusability: write once, call many times
- Abstraction: caller only needs to know what a function does, not how
- Easier debugging/testing: each function can be tested in isolation
Anatomy of a Function
int add(int a, int b) // prototype/signature: return type, name, parameters
{
int sum = a + b; // function body
return sum; // return statement -- sends a value back to the caller
}
int main()
{
int result = add(3, 4); // function call, with arguments 3 and 4
}
- Function prototype/declaration: tells the compiler the function's name, return type, and parameter types before it's used —
int add(int, int);
- Function definition: the actual body/implementation
- Function call: invokes the function with specific arguments
- Parameters (in the definition) vs Arguments (values passed at the call site) — a common terminology mix-up
- A function with return type
void returns no value; return; (with no value) is optional in that case
Standard Library vs User-Defined Functions
- Standard library functions: pre-built, reusable functions provided by the language (e.g.,
strlen(), sqrt())
- User-defined functions: programmer-written, promote modularity and reuse
Parameter Passing
- Pass by value: a copy of the argument is passed; changes inside the function do NOT affect the original variable
void increment(int x) { x++; } // caller's variable unchanged after this returns
- Pass by reference: the function receives a reference/alias to the original variable; changes DO affect the original