Functions in C Programming
Functions are reusable code blocks. They perform specific tasks.
This modularity enhances code reusability and readability.
Functions are like machines, processing inputs and producing
outputs.
Key Uses of Functions
Modular Programming Code Reusability Abstraction
Functions break down large Write a function once, call it Functions hide complex details
programs into manageable pieces. multiple times. Validating user behind a simple interface. This
This improves organization. input is a good example. makes the code easier to use.
Parameter Passing: Pass by Value
1 Copy of Value 2 Unaffected Original
A copy of the variable's value is passed. The Changes inside the function do not affect the
original variable is not changed. original variable. This is pass by value.
Parameter Passing: Pass
by Reference
Memory Address
The function receives the variable's memory address.
Use pointers.
Direct Modification
Changes inside the function affect the original
variable. Avoid this if you want to pass by value!
Passing Pointers to
Functions
Pointer Parameters
Functions can accept pointers as parameters. Allows
modification of original data.
Dereferencing
Use the * operator to access the value at the pointer's
address. Modify data.
Passing Functions as
Parameters
Function Pointers Callback Functions
Store the address of a function Functions passed as arguments.
in a pointer. Can then be They can then be executed in
passed to other functions. the receiving function.
Returning Values from Functions
Return Statement
1 Use return to send a value back to the caller.
Data Type
2 Match the function's declared return type.
Single Value
3 Functions can return only one value.
Example: Add Two Numbers
Here's a simple C function to add two numbers:
int add(int a, int b) {
return a + b;
}
This function takes two integers as input. It returns their sum as an integer.
Example: Modify Variable
via Pointer
Here's a C function that modifies a variable passed by reference:
void increment(int *num) {
(*num)++;
}
This function increments the value of an integer using a pointer.
The original value changes.
Key Takeaways
1 Functions are 2 Pass by Value vs.
Essential Reference
Modularity, reuse, and Know the difference and
readability. implications.
3 Pointers are Powerful
Modify original data and pass functions.