Module 4: Chapter 6 - functions
The General Form of a Function
Definition
A function is a small program or program segment that performs a specific, well-defined task. Functions help divide a large program into smaller, manageable parts.
Purpose of Functions
- Break a program into independent and reusable segments.
- Each function performs one specific task.
- Improves program readability and maintainability.
- Functions operate independently but work together.
General Form (Syntax)
ret-type function-name(parameter list)
{
/* body of the function */
}
Explanation
- ret-type: Specifies the type of value returned by the function.
- A function can return any data type except an array.
- function-name: Name used to call the function.
- parameter list: Receives values passed to the function.
- If no parameters are needed, use
void.
Parameter Declaration Rules
- Each parameter must be declared with its own type.
- Parameters are separated by commas.
- Unlike variables, parameters cannot share a type declaration.
Example
f(int i, int k, int j); /* correct */
f(int i, k, float j); /* wrong */
Function Call Flow
- The
main()function is the starting point of a C program. - When a function is called, control transfers to the called function.
- The calling function is paused until the called function finishes execution.
- After execution, control returns to the calling function.
Types of Functions
1. Library Functions (Pre-Defined / Built-in)
Library functions are predefined functions provided by the C compiler. They perform common and standard operations and are written by the designers of the C language.
Key Points
- Stored in C standard libraries.
- Used to perform frequently required tasks.
- Reduce program complexity and development time.
Examples
sqrt(n): Computes the square root ofn.pow(x, y): Computesxy.printf(): Displays output on the screen.scanf(): Reads input from the keyboard.abs(x): Computes the absolute value ofx.
2. User-Defined (Programmer Defined) Functions
User-defined functions are functions written by the programmer to perform specific tasks based on program requirements.
Key Points
- Created to solve custom problems.
- Improve modularity and code reuse.
- Each function performs a well-defined task.
Example
main()is an example of a user-defined function.
2.1 User-Defined Functions
Definition
User-defined functions are functions created by the programmer to perform specific and well-defined tasks in a program. They help divide a large program into smaller, reusable, and manageable parts.
Why Use User-Defined Functions?
- Improve code readability and structure.
- Reduce repetition by reusing code.
- Make debugging and maintenance easier.
- Support modular programming.
Types of User-Defined Functions
Based on whether a function accepts arguments and/or returns a value, user-defined functions are classified into four types:
there are 4 types of User-Defined Functions
- No arguments, no return value: The function neither takes input nor returns any result.
- Arguments, no return value: The function takes input but does not return anything.
- No arguments, return value: The function does not take input but returns a result.
- Arguments and return value: The function takes input and returns a result.
1. No Arguments, No Return Value
This type of function neither accepts input from the calling function nor returns any value. It performs a task independently.
void display(void)
{
printf("Hello World");
}
2. Arguments, No Return Value
This type of function accepts input through arguments but does not return any value to the calling function.
void printSum(int a, int b)
{
printf("Sum = %d", a + b);
}
3. No Arguments, Return Value
This type of function does not accept any arguments but returns a value after performing a computation.
int getNumber(void)
{
return 10;
}
4. Arguments and Return Value
This type of function accepts input through arguments and returns a computed result to the calling function.
int add(int x, int y)
{
return x + y;
}
Key Points
- User-defined functions must be declared and defined by the programmer.
- They can be called multiple times from different parts of a program.
- The
main()function is also a user-defined function. - Function behavior depends on its parameters and return type.
Understanding the Scope of a Function
Definition
Scope defines where a piece of code or data can be accessed in a program. In C, a function creates its own scope, known as function (block) scope.
Function Scope
- Each function is a separate and independent block of code.
- The code inside a function is private to that function.
- Statements from other functions cannot directly access this code.
- You cannot jump into another function using
goto.
Local Variables
- Variables declared inside a function are called local variables.
- They are created when the function is called.
- They are destroyed when the function exits.
- Local variables do not retain values between function calls.
-
Exception: Variables declared with
staticretain their values but remain accessible only within the function.
Function Parameters
- Function parameters are also local to the function.
- They exist only while the function is executing.
- They receive values from the calling function.
- They behave like normal local variables.
Example: Function with Arguments
/* Returns 1 if c is found in string s, otherwise 0 */
int is_in(char *s, char c)
{
while (*s)
if (*s == c) return 1;
else s++;
return 0;
}
Explanation
sandcare formal parameters.- They are accessible throughout the function.
- The function checks whether character
cexists in strings. - Returns
1if found, otherwise returns0.
Additional Notes
- Functions have file scope.
- You cannot define one function inside another function.
- This is why C is not a fully block-structured language.
argc and argv — Arguments to main()
Definition
Command line arguments allow you to pass information to a program
when it is executed. In C, these arguments are received by the
main() function using two parameters: argc and argv.
Syntax
int main(int argc, char *argv[])
{
/* program code */
}
Meaning of argc and argv
- argc (argument count): Stores the number of command line arguments.
- Its value is always at least
1. - argv (argument vector): An array of strings.
- Each element of
argvstores one command line argument. - All command line arguments are treated as strings.
Important Points
argv[0]always contains the program name.argv[1]contains the first argument.argv[2]contains the second argument, and so on.- Numbers passed as arguments must be converted using functions like
atoi().
Simple Example
Program that prints your name:
int main(int argc, char *argv[])
{
if (argc != 2) {
printf("You forgot to type your name");
return 1;
}
printf("Hello %s", argv[1]);
return 0;
}
How to Run
- Command:
program Tom - Output:
Hello Tom
Argument Separation Rules
- Arguments are separated by spaces or tabs.
- Commas and semicolons are not separators.
- Strings with spaces can be enclosed in double quotes.
Accessing Characters in Arguments
argv[t]accesses the tth argument.argv[t][i]accesses the ith character of that argument.
Uses of Command Line Arguments
- Passing filenames to programs.
- Providing startup options or modes.
- Making programs suitable for batch execution.
- Giving programs a professional and flexible interface.
Additional Notes
- The names
argcandargvare conventional, not mandatory. - You may use different parameter names.
- Some compilers may support extra parameters to
main().
The return Statement
Purpose of return
- Ends the execution of a function and transfers control back to the caller.
- Can optionally return a value along with exit.
Key Points
- Used inside functions to stop execution immediately.
- A function may contain multiple
returnstatements. - If function has a return type (non-void), return must pass value of same type.
- Without return in
voidfunction → control returns automatically at}.
Syntax
return; // no value returned (used in void functions)
return value; // returns a value
Example
int sum(int a, int b) {
return a + b; // returns result
}
void show() {
printf("Hello");
return; // optional here
}
What Does main() Return?
Understanding return type of main()
main()returns an integer value to operating system.return 0;indicates successful execution.- Returning a value from main is same as calling
exit(value). - If not returned explicitly, most compilers return 0 automatically — but not guaranteed.
Syntax
int main() {
/* code */
return 0; // success
}
Example
int main() {
printf("Program executed successfully");
return 0;
}
Return meaning
0→ Success- Non-zero → Error or abnormal termination
Recursion
What is Recursion?
- When a function calls itself, it is called recursion.
- Helps solve problems that can be broken into smaller subproblems.
- Must contain a base condition to stop infinite calling.
Syntax
return-type function_name(parameter) {
if(base_condition)
return value; // stopping condition
return function_name(modified_parameter); // recursive call
}
Example - Factorial using Recursion
int fact(int n) {
if(n == 1) return 1; // base case
return n * fact(n-1); // recursive call
}
How recursion works?
- Each recursive call creates new memory for variables on stack.
- Returns step-by-step when base condition is met.
- Too many recursive calls may cause stack overflow.
Advantages
- Simplifies complex problems (tree/graph traversal, quicksort, factorial, etc.).
- Code becomes cleaner and easier to visualize.
Disadvantages
- Slower than loops due to repeated function calls.
- Might consume more memory.
- Requires careful base condition handling.
Function Prototypes
Definition
A function prototype declares a function's return type and parameter types before its use. Prototypes enable the compiler to perform strong type checking on function calls (number and types of arguments).
Why Use Prototypes?
- Detect mismatched argument types or wrong number of arguments at compile time.
- Make code safer and easier to maintain, especially across multiple files.
- Required in C++ and strongly recommended in modern C (C89 and later).
General Syntax
return_type func_name(type param1, type param2, ..., type paramN);
Notes on Syntax
- Parameter names are optional in the prototype but helpful for readable error messages.
- If a function takes no parameters in C, use
voidin the prototype:float f(void); - An empty parameter list like
int f();in C means "no information given" (old-style)—avoid it. - The only function that does not require a prototype is
main()(it is the program entry point).
Example: Prototype that Catches a Type Error
/* Prototype enforces the argument must be int * */
void sqr_it(int *i); /* prototype */
int main(void) {
int x = 10;
sqr_it(x); /* compiler error: expects int * */
return 0;
}
void sqr_it(int *i) {
*i = *i * *i;
}
Example: Definition Used as Prototype
#include <stdio.h>
/* If defined before use, this serves as the prototype */
void f(int a, int b) {
printf("%d ", a % b);
}
int main(void) {
f(10, 3);
return 0;
}
Best Practices
- Always place prototypes (or headers with prototypes) at the top of a file or in a header (
.h) for multi-file projects. - Use full prototypes (with parameter types) to avoid old-style declarations and subtle bugs.
- Include prototypes when porting old C code to C++—C++ requires them.
Summary
- Prototypes improve compile-time checking and program robustness.
- Use
type name(type1, type2, ...)andvoidfor no-parameter functions in C. - Prefer prototypes in every C program—especially when working across multiple files.
Declaring Variable Length Parameter Lists
In C, you can declare functions that accept a variable number of arguments.
A common example is the printf() function. To specify a variable argument list,
the function declaration ends with three periods ..., known as an ellipsis.
Prototype Format
At least one fixed parameter must be present. The ellipsis indicates additional optional arguments.
int func(int a, int b, ...);
- The function must have at least one named parameter.
- Additional parameters beyond those specified can vary in count and type.
- This is used in standard library functions like
printf()andscanf().
Invalid Declaration Example
A function cannot have only ellipsis without fixed parameters:
int func(...); /* X illegal */
Variable-length parameter lists are powerful when argument count may differ,
but require careful handling using macros like va_list, va_start,
and va_arg from <stdarg.h>.
The inline Keyword
In C99, the keyword inline can be used with function declarations to suggest that
the compiler should optimize the function by expanding its code directly at the call site
rather than performing a usual function call. This can reduce overhead and improve execution speed,
especially for small functions.
How it Works
- When declared as
inline, the function code may be substituted directly where it is called. - It helps reduce function call overhead for short, frequently used functions.
- Important: The compiler may ignore the inline request based on optimization decisions.
inline int square(int x) { return x * x; }
The use of inline is beneficial when performance is critical,
but it is ultimately a suggestion, not a command—compilers may or may not expand the function inline.