C Functions: A Guide to Code Reusability
Discover what a function is in C programming—a block of code that executes only when called. Functions allow you to pass data, known as parameters, to perform specific actions, making them essential for code reusability. By defining your code once and using it multiple times, you can streamline your programming efforts and improve overall efficiency.
C Functions
What is a Function?
A function is a block of code that runs only when it is called. You can pass data, known as parameters, into a function to perform specific actions. Functions are crucial for reusing code—define the code once, and use it multiple times.
Predefined Functions
You've already been using functions! For example, the main()
function is used to execute code, and the printf()
function outputs text to the screen.
Syntax
int main() {
printf("Hello World!");
return 0;
}
Output
Hello World!
Creating Your Own Function
You can declare (create) your own function by specifying its name, followed by parentheses ()
and curly braces {}
. Inside the braces, you define what the function should do.
Syntax
void myFunction() {
// code to be executed
}
Explanation:
myFunction()
is the name of the function.void
means the function does not return a value (you will learn more about return values in the next chapter).- Inside the function's body, you define what the function does.
Calling a Function
Functions are not executed immediately. They are "saved for later use" and will run when they are called. To call a function, write its name followed by parentheses ()
and a semicolon ;
.
Syntax
void myFunction() {
printf("I just got executed!");
}
int main() {
myFunction(); // call the function
return 0;
}
Output
I just got executed!
You can call a function multiple times:
Syntax
void myFunction() {
printf("I just got executed!");
}
int main() {
myFunction();
myFunction();
myFunction();
return 0;
}
Output
I just got executed!
I just got executed!
I just got executed!
Calculate the Sum of Numbers
Functions allow you to perform almost any task. In the example below, we create a function to calculate the sum of two numbers. You can execute this function whenever needed by calling it.
Syntax
void calculateSum() {
int x = 4;
int y = 7;
int sum = x + y;
printf("The sum of x + y is: %d", sum);
}
int main() {
calculateSum(); // call the function
return 0;
}
Output
The sum of x + y is: 11
This example demonstrates a simple function that performs calculations. In the next chapter, you’ll learn how to make functions even more flexible by passing parameters.