What Are Functions?
Functions are the building blocks of modular C programs. A function encapsulates a reusable piece of logic that takes inputs (parameters), performs operations, and optionally returns a result.
c
Declaration vs Definition
Function Declaration (Prototype)
A declaration tells the compiler that a function exists, what parameters it takes, and what it returns — without providing the body. Declarations typically go in header files or at the top of a source file.
c
Function Definition
A definition provides the actual implementation:
c
Why separate them? In multi-file projects, the prototype goes in a.hheader file so other files can call the function. The definition goes in a single.cfile. This prevents duplicate definitions while allowing cross-file access.
Return Types
Every function specifies what type of value it returns:
c
Warning: If a non-void function doesn't execute areturnstatement, the behavior is undefined. The compiler may warn you, but won't stop you.
Parameters
Pass by Value
In C, all arguments are passed by value — the function receives a copy. Modifying the parameter inside the function doesn't affect the original variable.
c
Arrays as Parameters
When you pass an array to a function, it decays to a pointer. This means the function can modify the original array, but it loses size information.
c
Tip: Always pass the array size as a separate parameter. There's no way to recover the size inside the function —sizeof(arr)will give you the pointer size, not the array size.
Forward Declaration
If you define functions after
main(), the compiler won't know about them when it encounters the call. Use forward declarations to fix this:c
Practical Example: String Utilities
c
Summary
| Concept | Key Point |
|---|---|
| Declaration | Tells the compiler about the function signature |
| Definition | Provides the actual implementation |
| Return type | int, double, void, etc. |
| Pass by value | Functions get copies of arguments |
| Array decay | Arrays become pointers when passed |
| Forward declaration | Declare before main, define after |