Showing posts with label main. Show all posts
Showing posts with label main. Show all posts

Tuesday, 15 March 2011

Back to basics

So I've been getting some comments and messages about my posts being too advanced, So I've decided that it would probably make more sense to start C from the beginning. In this post, I'll show you how to write a basic "Hello World!" program and explain the ins and outs of it. Some things will just be touched on right now and more fully explained in later posts.

#include<stdio.h>


int main()
{
    printf("Hello World!");
    return 0;
}

To fully understand how the program works, I'll explain its components.


#include<stdio.h>

#include is a macro. This particular macro goes and finds a file on your computer, in this case stdio.h. This file is what we call a header file. Basically, this file contains a bunch of function definitions (again, more on this later). The #include macro tells the program to go look in the folder on your computer containing your standard C library header files and to find stdio.h. When you hit the "build" button, the compiler will take your source code and compile it into machine code, but even before that, something called the preprocessor (we'll mention this again much later) will physically copy all the text from stdio.h into your program. Now when your program gets compiled, the compiler sees all this code in your program, so it actually becomes a part of your program.

int main()
{


}

Functions are very important in any programming language. Every program in C must have a main function. Everything contained within the curly brackets will be code executed during runtime.

printf("Hello World");

This is a call the function which prints to the screen. This printf function is defined within the stdio.h file. Having included that file, we are able to call this function. Here, we can see that the text we are printing to the screen is "Hello World".

return 0;

To indicate to the operating system that the program has terminated successfully (ie. No runtime errors occurred/The program did not crash/etc) we return 0 at the end of out main. This signifies the end of our program.

I hope this has been useful to those not yet fully comfortable with C.