-
Notifications
You must be signed in to change notification settings - Fork 0
section6_functions
We have seen some functions already. One that you all the time for every C program is the main
function, which we already explored. Other used functions are printf
and scanf
which someone implemented by us and it's available through the Standard Library. Functions are extremely useful and a must-use in the C language.
Every function should have a single task: solve a particular problem. When you program in C and you intend to solve a problem, as you are reasoning, you might realize you have several tasks to perform in order to solve the whole problem. In C programs, that's exactly the idea. Given a big problem, you break it into smaller problems and create functions that should handle each of those problems independently. Then, each function might use other functions to solve its problem. In the end, the set of functions you defined when combined are able to solve the major problem.
This art of programming has its benefits:
-
Code organization. Instead of writing the whole code in the
main
function, you break the problem in small tasks and iteratively create a function that attacks a particular task. This lets you incrementally create the program and test it. -
Re-use code. This is a very important point. Imagine a function from the standard like
sqrt
which let's compute the square root of a number. This is a very common problem. Why would you and everyone in the world write it's ownsqrt
version, probably some implementations more efficient than others, when you can use an implementation already available? This also holds for your own code. You might end up creating a set of functions that solve some problem. Imagine having repetitive code in your program or even across different projects. First, your code quickly becomes extremely verbose. Second, it's extremely hard to maintain! If all of sudden you detect a bug, you would have to manually update the code wherever you use it! This idea of reusing code is simple but very powerful. For now we are working on a single source code file, but you can split your code across different files, and for instance, create a library that solves a certain problem and use it on different programs. Not only you would use the library without caring about the implementation details (you wrote the code, tested it, it works, so you don't need to worry, just it), but if you find a bug, you fix it in the library without affecting your main projects.
return_type function_name(parameters_list)
{
// statements
return ;
}
Every function has a name and a return type. Moreover, it might have a list of parameters, but it's optional. Inside the function body, you have a set of statements that might use data from the parameters list, if any, do some computation and finally produce a result. That result can be passed via the return
statement.
Regarding the return, functions don't necessarily need to produce a value to be returned. This functions have a void
return type, which means it won't return anything.
#include <stdio.h>
int add_numbers(int a, int b); /* function prototype. This DECLARES the function */
int main() {
int a, b, sum;
printf("Insert the first operand ? ");
scanf("%d", &a);
printf("Insert the second operand ? ");
scanf("%d", &b);
sum = add_numbers(a,b);
printf("%d + %d = %d", a,b, sum);
/* Alternative -> printf("%d + %d = %d", a,b, add_numbers(a,b)); */
}
int add_numbers(int a, int b) { /* function definition. This DEFINES the function */
return a+b;
}
Let's analyze the code.
After the #include
statement, we declare a function called add_numbers
that returns an integer value and has two parameters, a
and b
, both of type int
, forming the parameters list. This is the function prototype or the function declaration. We say Hey, this is a function called add
, it produces a result of type int
and expects two arguments of type int
. Notice we don't have a function body, yet. This is a pure declaration in advance.
The function definition syntax consists of the function prototype followed by the function body, inside curly brackets. The function body is just a set of statements that compute something.
On the function definition, you must also specify what the function returns, unless it's a void
function. In functions where the program flow is not sequential, due if
statements, for example, you must ensure whatever path the code takes it returns something meaningful. Otherwise, either the compiler will throw an error, or if the compiler is very passive the function return will be garbage.
/* Example illustrating that the program always returns something meaningful despite the control flow */
int foo(int a) {
if(a > 0)
return -a;
else
return a;
}
Some terminology to retain:
- Declaring a function tell the compiler about the existence of a function that has some name, has some parameters and returns a certain data type.
- Defining a function is writing the function body, i.e. what statements the function will execute and what value it will return. Implicitly this is also declaring the function.
Below are two examples of void functions. They don't produce any value, they just print a message on the console.
void printError() {
printf("Something went wrong!");
return;
}
void printError() {
printf("Something went wrong!");
The difference between both examples is that the second one omits the return
statement, which is optional within void
functions.
The general syntax to call a function is
function_Name(argument1, argument2, ...);
function_Name2(); // this function doesn't have a parameter list on definition
If you want to save the function return value, you can assign to a variable as follows (as long data types match):
variable = function_Name(argument1, argument2, ...);
It's worth mentioning that even if the function returns values, it can be ignored, it's not mandatory to store the result in a variable.
It's pretty simple. You just type the function name followed by ()
. Inside the parentheses you pass the arguments, if required by the function definition.
- Parameters are the variables on the function definition
- Arguments are the actual value/variable passed to the function
Soon...