User-Defined Functions in C
A function is a block of code that performs a specific task and can be reused whenever needed. Functions help break a large program into smaller, manageable parts and eliminate code repetition. Types of functions in C:- Predefined Functions — Built-in, e.g.
printf(),scanf(),sqrt() - User-Defined Functions — Created by the programmer
Structure of a Function
1. Function Declaration (Prototype / Signature)
Tells the compiler the function’s name, return type, and parameter types — without a body. Placed beforemain().
2. Function Definition
The actual function body — what the function does.3. Function Call
Executes the function from somewhere in the program.Complete Example
Types of Function Based on Arguments and Return
| Type | Arguments | Returns |
|---|---|---|
| No argument, no return | None | None |
| No argument, with return | None | Yes |
| With argument, no return | Yes | None |
| With argument, with return | Yes | Yes |
Why Use Functions?
- Reusability — Write once, use anywhere in the program
- Modularity — Break complex programs into smaller pieces
- Readability — Code becomes easier to understand
- Easy debugging — Isolate and fix bugs in specific functions
- Avoid repetition — No need to rewrite the same logic
Key Rules
- Arguments in C are passed by value by default (changes inside the function don’t affect the original unless pointers are used)
- A function without a
returnstatement that has a non-void return type will return a garbage value - Function prototypes allow defining the function after
main()