Functions!
What is a Function?
A function is a block of code that performs a specific task. Instead of repeating code, you can call a function whenever you need it. Functions can take inputs (parameters), perform actions, and return outputs.
Why Use Functions?
Reusability: Write once, use multiple times.
Modularity: Break complex programs into simpler pieces.
Maintainability: Easier to manage and debug.
Organization: Makes code more readable.
Function Syntax
Here's the basic structure of a function in C:
returnType: The type of value the function returns (e.g.,
int
,float
,void
).functionName: The name you give the function.
parameterType: The type of input the function takes.
Function body: The code that performs the task.
Example of a Simple Function
Let’s create a function that adds two numbers and returns the result.
Types of Functions
Functions with No Parameters and No Return Value
These functions perform a task but don't take input or return anything.
Example:
Functions with Parameters but No Return Value
These take inputs but don’t return a value.
Example:
Functions with Return Value but No Parameters
These return a value but don’t take any inputs.
Example:
Functions with Both Parameters and Return Value
These take inputs and return a value, like the
add
function above.
Function Declaration vs. Definition
In C, you can declare a function before you define it. The declaration tells the compiler about the function's name, return type, and parameters, but not the actual implementation. This is useful when you want to define your functions later in the code.
Declaration Example:
Return Statement
The return
statement is used to exit a function and send a value back to the function’s caller.
Example:
Scope of Variables
Local Variables: Variables declared inside a function are local to that function. You cannot access them outside the function.
Global Variables: Variables declared outside all functions are global and can be accessed by any function in the program.
Example:
Passing Arguments: Call by Value
In C, arguments are passed to functions by value, meaning the function receives a copy of the variable, not the actual variable itself. Any changes to the parameter inside the function do not affect the original variable.
Example:
Practical Example: Factorial Function
Let’s create a function that calculates the factorial of a number (n! = n × (n-1) × … × 1).
Summary
Functions in C help organize your code and make it reusable.
A function has a return type, name, and parameters.
You can declare a function before defining it.
Functions can take input (parameters) and return output.
Variables inside functions are local, while variables outside are global.
Last updated
Was this helpful?