Chapter 2 *Basics Of A C Program

Table of Contents
2.1 Getting Started in C
2.2 The Characters Used
2.3 Summary
Contributed from The C DiskTutor by L. John Ribar. Converted to SGML and updated by Dave Chapeskie.

Note: This chapter is still in need of work, it's currently a near exact copy of the chapter from The C DiskTutor [Ribar, 1992].

This chapter needs to cover:

  • comments

  • expressions

  • statements

  • statement blocks

  • function calls



This chapter has two goals. The first goal is to give you a basic introduction to how C programs look, before we start with specifics in the following chapters. The second is to teach you to use the Posix environment to enter and run your first C program. Since this chapter is meant as an overview of C, do not try to learn all the concepts in one sitting; just remember the basic concepts for use in the following, more detailed, chapters.

C can be both a very simple and a very difficult language to learn. The simplest C program is very small:

    int
    main (void)
    {
        return 0;
    }

If you were to run this program, you would see that it doesn't do anything; but it is a valid C program. Before going on, you must understand the parts of this simple program.

Each function definition in C has a name (like ``main''), two parenthesis, and two curly braces. If there are parameters to be sent into the function, they are listed within the parenthesis. The actual program code for the function is placed between the curly braces. The details of these portions of a function are covered in the sections which follow.

2.1 Getting Started in C

C programs consist of one or more functions, each of which performs a sequence of events (A function is a group or sequence of C statements which are executed together). Every C program begins with a function called main. This is where program execution begins, and therefore is required in every C program.

Unlike many other languages, such as Pascal, in which the main routine usually has the same name as the program file, C requires all programs to start with main. However, no requirements are placed on the filename used to hold the main function; it can be any valid filename, usually ending with the .c extension.

Note in the simple C program above that two parentheses around the word void follow main. This shows that this is a C function. That means that main, like other C functions, can be called from another function. The void keyword indicates this function takes no arguments, parameters could have been listed here instead. Parameters are variables or values passed into the function and used for processing.

The main function can take an optional set of parameters. These parameters are used for reading the command line and environment (discussed in XXX). A program with parameters for the main function looks like this:

    int
    main (int argc, char *argv[])
    {
        return 0;
    }

You'll learn about parameters to main in chapter/section XXX.

Note that the braces ('{ and }) have no code between them. Normally, the actual program code would go inside those braces.

Here is another program; while it is still simple, it actually does something. Create the file hello.c with the following contents:

Example 2-1. Hello World program

    /* A small C program to print a message to the screen. */
    /* Written by L. John Ribar */(1)
    
    #include <stdio.h>(2)
    
    int(3)
    main (void)(4)
    {(5)
        printf("Hello world!\n");(6)
        return 0;(7)
    }(8)

Here is a step-by-step explanation of what the program does, and how the C language performs each of the required functions.

(1)
These first two lines are comments telling what the program is, and who wrote it. While they are shown as two separate comments here, the text could have been combined as a single comment like this, in order to reduce typing:
    /* A small program to print a message to the screen
       Written by L. John Ribar. */
(2)
This line tells the compiler to read the file stdio.h, and to include its contents into this file. stdio.h is a file known as a header file; it stores definitions used in many programs in one place so that they won't have to be re-typed each time. stdio.h is a header file which contains the information about input and output functions (see XXX for a more complete discussion).

The <> delimiters on the file name show that the file is a system file. System files come with the operating system or the compiler, and are stored in a special directory that the compiler knows about, and can find. If quotation marks had been used instead, like this:

    #include "stdio.h"
then the compiler would have searched the current directory for the header file, instead of the system directory. Your own header files will generally be included by using the quotation mark (or local) version.

(3)
This is the variable type returned by this function. The main function always returns an int which is used as the exit status of the program.
(4)
This is the start of the main program. As noted before, the main function could have been declared with parameters. main is a special function which allows you either to use or to ignore the parameters. Functions other than main will either always use parameters, or not have any parameters.
(5)
The first brace marks the beginning of the code of the main function. Notice how both this brace, and the one at the end of the program, are in column one, and that the code is indented. This format is consistent with the style we adopted in XXX for use in this book (see XXX for more information on indenting and programming style).
(6)
This line contains a call to the function named printf. In this case, a parameter -- the string Hello world!\n -- is sent into the function by placing it between the parentheses. printf is a very common function, and is used throughout the book; it is covered in full detail in XXX.

The \n at the end of the string is a shortcut notation for a carriage return, which makes the cursor move to the beginning of the next line on the screen, after the string is printed. This is like pressing the carriage return on a typewriter after typing a line.

(7)
Here we use the return statement to end the function and return the value zero. A value of zero returned from main as the program exit status indicates successful completion.
(8)
This brace marks the end of the main function, and in this case, the end of the program.

Note: Braces must always match up in C; each opening brace ({) requires a closing brace (}). If the compiler finds an uneven number of braces, it will flag it as an error, and you will need to find the missing, or extra, brace.

Once you have entered the program into a hello.c you're ready to compile it. From the command line type the following command:

cc -o hello hello.c

Assuming you've made no errors the command should run without producing any visible output. It will have created an executable file hello which you can now run.

After compiling and running this program, your terminal will look similar to this:

    % ls
    hello.c
    % cc -o hello hello.c
    % ls
    hello
    hello.c
    % ./hello
    Hello world!


This, and other documents, can be downloaded from http://opencbp.sourceforge.net/.

For questions about the Open C Book Project, read the documentation.