Functions
Functions in Procedural Languages like C
One of the important topics in procedural languages like C is functions. In languages like Java or C#, they are called methods. Regardless of what they are called, their job is the same. Imagine doing the same operation multiple times. Writing the same code for every instance would be quite cumbersome. Functions are designed to solve this problem. You define the operation once, and then you can call the function as many times as needed. The benefits of functions don't stop there.
Functions provide modularity. For example, let's say you've written a function to test if a number is prime, and you realize it's incorrect. You don't need to change the entire program—just fix the wrong function, and the program will work correctly. Additionally, moving the code of your functions to other programs is very simple.
Functions make your work easier. Imagine writing a program that reads data from disk, processes it, then converts the results into a graph to be displayed to the user, and finally writes the output back to disk. If you write this all from scratch, it would be hard to understand. You could add comments to make the code more readable, but it still wouldn't be enough. The best approach would be to break the program down into functional pieces. For instance, you could create a read_from_disk()
function to handle reading, a draw_graph()
function to display the graph, and a write_to_disk()
function for writing the results. The next time someone reviews your code, they will be able to quickly find what they need by looking at the relevant function. A structure broken into smaller, modular parts is easier to work with than dealing with thousands of lines of code.
In this article, we will explain functions.
The main()
Function
In all the code we've written so far, we've used the notation main()
. This expression refers to the main()
function. In C programming, the execution of code depends on whether it is inside the main()
function. Think of it as the starting point. Every program has only one main()
function. Other functions, libraries, or code segments are executed by being directly or indirectly referenced inside the main()
function.
To reinforce our understanding of the main()
function, let's write a program. Below, we'll create a program to draw the shape of a house:
/* Program to draw a house */
#include<stdio.h>
int main(void) {
printf(" /\\ \n");
printf(" / \\ \n");
printf(" / \\ \n");
printf(" / \\\n");
printf("----------\n");
printf("| |\n");
printf("| |\n");
printf("| |\n");
printf("----------\n");
return 0;
}
This program is simple. We had to use two backslashes \\
because the backslash character is special in C. Other than that, there’s nothing complicated about the code, so I won’t go into further explanation. The only important thing is that the program works inside the main()
function.
To summarize, the main()
function is a special construct. The program starts executing with the main()
function, and any other code is executed either directly or indirectly inside main()
.
Creating a Function
You can create your own functions. The functions you create are responsible for performing a task and can be reused multiple times when called.
Let's revisit the house example. Instead of writing everything inside the main()
function, what if we created separate functions to draw the roof and the walls? This way, we wouldn't have to repeat ourselves every time we needed to draw another wall or roof. Functions provide a solution to this problem. Let's refactor the previous code to use two functions for drawing the roof and the walls:
/* Program to draw a house */
#include<stdio.h>
// Function to draw the roof of the house
void draw_roof(void) {
printf(" /\\ \n");
printf(" / \\ \n");
printf(" / \\ \n");
printf(" / \\\n");
printf("----------\n");
}
// Function to draw the walls of the house
void draw_wall(void) {
printf("| |\n");
printf("| |\n");
printf("| |\n");
printf("----------\n");
}
// The main function
int main(void) {
draw_roof();
draw_wall();
return 0;
}
The code works the same way as before, but this time we are using functions. This program draws the same house as before, but now it's much cleaner and easier to modify. We have used functions to separate the tasks of drawing the roof and the walls.
The void
Keyword
In the examples above, you may have noticed the use of void
. The word "void" means "empty" or "invalid" in English, and in C, it is used to indicate that a function doesn't take any arguments. For instance, in the draw_roof()
and draw_wall()
functions, they don't need any input to do their job, so we can use void
in the function definition. In C, a function that does not take any arguments can be declared as void
.
The two following function definitions are equivalent:
void draw_wall(void) {
// Function body
}
void draw_wall() {
// Function body
}
Both versions work in the same way. The second method is more common and preferred, but the first one is also valid.
Argument Passing
In previous examples, our functions didn’t take any values from outside. We used void
to indicate that the function doesn't need any arguments. However, this is not always the case. Functions can take arguments, which are values passed to them from outside.
When defining a function, you specify what kind of data the function will accept. These variables are called parameters. The values passed to the function when it is called are called arguments. To clarify this, let's improve the house example. This time, we will allow the user to choose the characters used to draw the walls of the house.
/* Program to draw a house */
#include<stdio.h>
// Function to draw the roof of the house
void draw_roof(void) {
printf(" /\\ \n");
printf(" / \\ \n");
printf(" / \\ \n");
printf(" / \\\n");
printf("----------\n");
}
// Function to draw the walls of the house
// 'left' and 'right' are parameters of the function.
void draw_wall(char left, char right) {
printf("%c %c\n", left, right);
printf("%c %c\n", left, right);
printf("%c %c\n", left, right);
printf("----------\n");
}
// The main function
int main(void) {
char left_wall, right_wall;
printf("Enter the characters to use for the walls: ");
scanf("%c%c", &left_wall, &right_wall);
draw_roof();
// Passing arguments to the function
draw_wall(left_wall, right_wall);
draw_wall(left_wall, right_wall);
draw_wall(left_wall, right_wall);
return 0;
}
In this example, the draw_wall()
function now takes two arguments (left
and right
) which specify the characters used for the left and right walls of the house. The user is prompted to enter these characters, and then the draw_wall()
function is called with those values.
You can pass values directly to a function, as in the following:
draw_wall('*', '*');
This would use asterisks (*
) as the characters for the walls.
Checking if a Number is Odd or Even
Let's now create a function that checks if a given number is odd or even:
/* Program to check if a number is odd or even */
#include<stdio.h>
// Function to check if the number is odd or even
void check_odd_or_even(int number) {
if (number % 2 == 0) {
printf("%d is an even number.\n", number);
} else {
printf("%d is an odd number.\n", number);
}
}
int main(void) {
int entered_number;
printf("Enter a number: ");
scanf("%d", &entered_number);
check_odd_or_even(entered_number);
return 0;
}
In this example, the check_odd_or_even()
function accepts an integer and prints whether the number is odd or even.
Local and Global Variables
In the examples above, all the variables we defined were local to the function in which they were declared. This means that the variables are only accessible within the function and cannot be accessed from outside it. For instance, the variable a
inside the function calculate_cube()
is different from the variable a
inside the main()
function. Therefore, changing a
inside one function will not affect the value of a
in the other.
If you want a variable to be accessible across multiple functions, you can define it globally. A global variable is one that can be accessed from any function in the program. Here’s an example:
#include<stdio.h>
// Global variable
int result = 0;
// Function to calculate the square of a number
void calculate_square(int number) {
result = number * number;
}
// Function to calculate the cube of a number
void calculate_cube(int number) {
result = number * number * number;
}
int main(void) {
int number;
printf("Enter a number:
"); scanf("%d", &number);
calculate_square(number);
printf("The square of the number is: %d\n", result);
calculate_cube(number);
printf("The cube of the number is: %d\n", result);
return 0;
}
In this program, we used a global variable `result` that holds the result of both the square and cube calculations. Since the variable is global, it can be accessed and modified by all functions in the program.
Yorumlar
Yorum Gönder