learn c with me - week 1

site under construction

Let's build our very first C program from scratch.

Firstly, we need to create the .c file, where we will write our code. In my case, the following command does the job:

            
touch hello.c
            
        

The file hello.c is now our canvas we can use to write the code. The name of the file can be virtually anything, but I recommend you to stick with hello or any other mnemonic name.

The main function

As you might know, C is a compiled language, which means it's converted from human readable source code to machine code in the process of compilation. Because of this, every executable C program requires the main function, as the clear starting point.

            
int main(void)
{

}
            
        

From the left, we have the int keyword, claiming that our main function returns an integer value after executing. While it's no longer enforced by C, it's good practice to add a return value to the main function. It both improves readability and possible compatibility with older systems, so why not add it?

            
int main(void)
{
    return 0;
}
            
        

Why 0? Think of it as when we launch our program, the operating system executes the machine code and waits for the response to the question "is something wrong with this program?". The value 0 (false) means that everything was right and now the program finished everything it had to do and now the operating system can take care of all low level stuff like freeing up memory and other computer things, while any other value but 0 will mean true, giving an operating system the opportunity to yell an error message at us. Using different values for different errors improves readability and ease of troubleshooting even further.

Next, we have main(void), which is the name, reserved exclusively for the main function, while the void inside parenthesis is the indicator of what type of data this function accepts as input (argument). The void is the data type literally meaning there is no data, meaning that the main function doesn't expect any argument to work with and we shouldn't provide any.

Note: While working with the code of other people, there is a great chance that you will encounter some sort of cryptic main function signature looking like this:

int argc, const char * argv[]

We can roughly translate it to "function main accepts 2 arguments, the first one is the argc in the form of an integer number and the second one is the argv in the form of the constant array of characters". In a nutshell, the argc is the number of the arguments passed along with the program, whilethe argv stores them in the form of a list you can read, analyse, iterate over and do all the things you would like to do with an array.

Another element are the curly braces (this -> {}). They are holding all the code belonging to the parent element (the main function in our case) making it easier to read and understand code both by humans and the compiler making its job easier and more efficient. Think of curly braces as twins, they don't really like to be alone. They need eachother to work properly.

Who would win? A computer program with millions of lines of code or one curly boy with no friend?

Second note: The position of curly braces is purely a matter of preference. You can put them wherever you like;

                
int main(void)
{
//this works
}

int main(void){
//this will work as well
}
                
            

The last element here we can't forget about is the semicolon (;), which job is to separate expressions, like the dot at the end of sentences making them more readable. Its presence might be annoying at first, especially if you are coming from languages like python, but at some point you will realise it's more reliable than just whitespaces.

That would be everything in this section, but it's not all for today! At the end of the day, a program that doesn't return anything would be useless, wouldn't it?

Output operations

The most basic way of returning text back to the user is the printf function. The name stands for "print formatted" which is pretty much self explanatory; today we will get just into printing, but I am sure in the future we will also dive into the formatting part, because it's pretty useful.

Usage of printf is pretty straightforward

printf("text you want to
display inside double quotes"
,
formatting parameters (if any)
);

So now let's use it to make our hello program, well, say hello

int main(void) { printf("hello") return 0; }

Now you would probably like to run your program and see the results, but wait, something is not right.

error: expected ';' after expression

Ah, we forgot about the semicolon. Let's fix that

printf("hello");

Now we should be good to go, but still something is not working as expected.

error: implicitly declaring library function 'printf' with type 'int (const char *, ...)' [-Werror,-Wimplicit-function-declaration]

It seems like we want to access the function that doesn't exist. But why its that? Well, the compiler its not psychic, even if the printf function is provided by C standard library, the compiler doesn't know about it, until we explicitly tell it where it has to look for the printf function body. Including every built-in function directly into C would be overkill in most use cases, especially if we look at the fact C was first developed in times when every byte of memory was important and every byte less used by the program would make a difference, so the developers of C decided to divide the standard library into a collection of atomic shards, that can be used independently in the program and then added to the code in the linking process in compilation time. It might sound complicated, but in reality it's easier than one might think.
Just add #include <stdio.h> on top of the content of hello.c or whatever you named your c file.

                    
#include <stdio.h> 
int main(void)
{
    printf("hello");
    return 0;
}
                    
                

The #include <stdio.h> is also pretty self explanatory. It says to the compiler "include stdio.h file in this place".
But what is <stdio.h>?
stdio.h is the header file (more about them in the future, we will even write one by ourselves) named stdio; which stands for *standard input and output*, which is the standard library piece responsible for handling inputs and outputs, like the printf function we already used or scanf function for handling user's input, but more about it in the future. Anyway, our program should now be ready to compile and run. It compiles without any issues, but there is still something weird in it;
After running we receive the following output:

helloProgram ended with exit code: 0

As mentioned at the beginning of the post, code 0 means everything was right, so we don't have to worry about it, but why the is the hello just put before it, in the same line? It would be more readable to split the output generated by the program itself, from the output generated by the terminal launching our program.

To do this, we need to modify the "hello" string a bit, by adding \n also known as escape sequence or escape character. Escape sequences are basically reserved sequences of most likely 2 characters used to represent special characters like the space, tab or new line buttons on our keyboard, or characters used by the language itself, so using them directly would cause unexpected behaviours in our program, like the * or % symbols. You can find a complete list of them here.
Right now we only need to use the \n standing for new line character, which will be the solution to our tightly displayed text. Just add it at the end (or wherever you want to have your new line character inserted) of the string. It works pretty much the same way like <br> html tag.

                    
#include <stdio.h> 
int main(void)
{
    printf("hello");
    printf(
"you can put new\nline character\n"); printf("whenever\nyou\nwant.\n"); return 0; }
here's the output:
hello

you can put new

line character

whenever

you

want.

Program ended with exit code: 0
                

Cool? Now you can unleash your creativity by making your very own hello, world program.

Exercise

Write your own version of hello, world program. It can display any text you like, however you want it to be displayed. Maybe some ascii art? It's your time to push the printf function to its limits.

If you are still reading this, I want to thank you for all your time spent reading this post.
At the same time, I also want to sincerely thank all those involved in the process of improving the text, and all those who gave me tips directly related to the content itself, and those who supported me from the very beginning in this creative process. Without you, this series would never have made it to publication, and even if it did, never in such quality.
As always, see you next time and take care of yourself. Go ahead and do finally the laundry you are procrastinating for the last 2 days.

Sleep well and stay tuned,
Laura

                    
+-------------------------------------+
| #         ##   #    # #####    ##   |
| #        #  #  #    # #    #  #  #  |
| #       #    # #    # #    # #    # |
| #       ###### #    # #####  ###### |
| #       #    # #    # #   #  #    # |
| ####### #    #  ####  #    # #    # |
+-------------------------------------+