C can be a very intimidating language especially if you are coming from other languages like Python and JavaScript where a lot of heavy lifting is done under the hood. For example in Python, you don’t have to allocate or reallocate memory just to grow or shrink a list. I think the most popular difference between Python and C is typecasting, what do I mean?
Normally in C, you have to do something like int number = 3;
when you want to declare a variable called number but in Python, you just do number = 3
. Luckily for me, I learned C first thanks to Harvard CS50 course which went in-depth into the C language and helped me understand it better. This made it easier for me to understand other languages later on.
Now, I’m not here to talk about the differences between these languages, I am more interested in functions. I haven’t done any programming for over a year, so when I came back to it, I had to revise everything I had learned starting with C. Without much further ado, let’s look at functions in C.
Defining a function
In C, a function is first written by specifying its return data type which can be int, char, bool, float, or even void. After that, the next thing is the name of the function which can be anything you want, and then you list out the parameters, starting with their types and separated with a comma, for example; (int a, int b)
. The next thing is to write out what the function actually does inside a curly bracket {}. Here is a simple function definition:
int sum(int a, int b) {
int add = a + b;
return add;
}
As usual, we started with specifying the return type of the function which is an int, then the name of the function which we call sum, and then the parameters which are int a and int b, and we have what the function does inside the curly brackets which is just to add two numbers and return the result.
If the return type is void, then there is no need to return any value from the function. Also, if you try to return a data type different from the return type, it will result in an error. What do I mean? Let’s look at the sum function I wrote earlier and change something
int sum(int a, int b) {
int add = a + b;
return “add”;
}
You can see that I have added quotation marks to “add” which makes it now a string, it is no longer the variable add which is an int. The return type of that function is an int but I am now trying to return a string, what will happen when I run the code?
functions.c:15:12: error: incompatible pointer to integer conversion returning 'char[4]' from a function with result type 'int' [-Werror,-Wint-conversion]
return "add";
^~~~~
1 error generated.
Declaring a function
While this isn’t exactly compulsory to do so (I will show you why in a bit) it’s indeed better and in line with best practices if you declare a function but what does this even mean? Declaring a function means leaving a prototype for the compiler to know that a function exists in your code before it is defined
C reads your code from top to bottom and usually, we start with the main() function which provides structure and starting point for C programs. It is in this main() function that a function is being used (or called) but the function is defined outside of main. As I said earlier, it isn’t compulsory to declare a function because you can just define the function above the main() function and the code will still work because it will read from top to borrow. Example:
// definition for the sum function
int sum(int a, int b) {
int add = a + b;
return "add";
}
// the main function
int main(void)
{
int a = 2;
int b = 3;
int result = sum(a, b);
printf("%i\n", result);
}
This will indeed work and I will get 5 as the answer (2 + 3) but what happens when you have lots of functions in your program? It will look very messy because you will just start piling all of them on top of the main() function. So, it’s much better to declare the function above main(), then define it below main() like so;
int sum(int a, int b);
int main(void)
{
int a = get_int("first number: ");
int b = get_int("second number: ");
int result = sum(a, b);
printf("%i\n", result);
}
int sum(int a, int b) {
int add = a + b;
return add;
}
This code looks similar to the previous one but the major difference is that the function definition is no longer above main(), instead what we have here is a simple function declaration. This tells the compiler that the sum function exists somewhere in the code and it should remember to check for it.
int sum(int a, int b);
A function is declared similarly to the way it is defined, just that there is no need for the curly braces and everything within it, that comes in the function definition after main() function. One thing to note is that the function declaration and definition should be the same in the sense of return type and parameter data type. But the parameter names can differ, like this; int sum(int num1, int num2)
.
Calling a function
A function call simply means using the already defined function to solve a problem within the code. It is essentially using the function for what it is intended for and this can be done by simply just writing the name of the function, and passing it the required parameters in the form of values. By calling a function, we are simply transferring control to it to perform the instructions within those curly brackets and get back a result from it.
int a = 2;
int b = 3;
int result = sum(a, b);
printf("%i\n", result);
What I did in the above code was to create two variables called a and b with 2 and 3 as their values respectively. Then I created another variable called result, which will hold the result of the sum() function. The sum(a, b)
is passed two parameters which are the variables a and b. Copies of these variables are passed to the sum() function we defined earlier, and after carrying out the instructions, it returns 5 as the result.
The 5 gets returned to the same position as sum(a, b)
. So, think of this line of code int result = sum(a, b)
now becoming int result = 5
after the function has done its work. Now, do note that the return value of a function must be stored in a variable of the same type. What this means is that I can’t store 5 in a variable like float result
or char result
. In essence, I can’t do something like this;
float result = sum(a, b);
I will get back an error because the return value of the sum() function is an int and I am trying to store it in a float. Of course, we don’t have this sort of problem in a language like Python, and this is what everything we have done will look like in Python
def main():
a = 2
b = 3
result = sum(a, b)
print(result)
def sum(a, b):
add = a + b
return add
main()
Pretty straightforward isn’t it? No need for a function declaration, adding int to a and b, or specifying the return and parameter types in the function definition, it looks much easier to do. Whereas in C, the entire code looks like this;
#include <stdio.h>
#include <cs50.h>
int sum(int a, int b);
int main(void)
{
int a = 2;
int b = 3;
int result = sum(a, b);
printf("%i\n", result);
}
int sum(int a, int b) {
int add = a + b;
return add;
}
Functions in C I will admit are a lot similar to what we have in Python and javascript (not surprising seeing as C is their mother) aside from a few differences and those differences are what makes me prefer how they work in Python and javascript. There are some other things I didn’t talk about such as function pointers and scope and I will probably do that in another article.
Thanks for reading
Connect with me on:
Twitter: @kushyzeena
Readcash: @kushyzee
Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!
Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).
You may also include @stemsocial as a beneficiary of the rewards of this post to get a stronger support.
I also watched a bit of Havard's CS50 video too when I was learning about data structures and algorithms at one point and I decided to learn a bit of C.
It was really interesting to see how a lot of the programming tools that I took for granted in Python really work under the hood, and it really blew my mind. I think I should get back to learning about C since I stopped a while back.
Learning C first made learning python a lot easier as most of the concept in C are also in python but a lot easier. You can still resume learning C but it might be a bit difficult if you're already used to programming with python