Skip to main content Skip to navigation

2.1 Introduction

Code format

The basic layout of a C program is as follows

# preprocessor directives
# declarations

main()
{


body of program...


}

function_1
function_2
etc

The general structure of a function (called function_name in this example) is as follows

type function_name (parameters)
{
local variable declaration

body of function code

}

If the type definition is omitted, c assumes that the function returns an integer type variable - so be careful! This also applies to the main body of the program. You can find out more about functions later.

A first code

Putting it into Practice:

Here is a trivial first code that includes some output. Using emacs, open a file called hello.c, and put the following into this file. Then save and quit emacs.
#include <stdio.h>

/* Main Function
 *   Purpose: Controls our program, prints Hello, World!
* Input: None
* Output: Returns Exit Status */
int main() {
printf("Hello, world!\n"); return 0; }
Now you should compile this code. At the prompt, type
gcc hello.c -o hello
This should have compiled without error, and made an executable called hello . This executable is now ready to run. To run it, type at the prompt (and then hit return)
./hello
On your x-term, you should see the output Hello, world!

Notes on your first code

  • The first line in the code is a preprocessor directive, in particular, it refers to an header file. Header files are very important, C really can't do very much without including these files. These files reside in /usr/include on most machines. You should check where your include files are kept! The file stdio.h is the header file used for standard input/output - so you will usually find it in most C codes!
  • The printf() command is a standard C function - this statement will not work if you do not include stdio.h. The statement to be printed is contained within double quotation marks - also standard practice. Furthermore, take note of the \n at the end of the printed statement - this signifies a newline (same effect as hitting return, otherwise known as a carriage return).
  • Comments are very important in all code. In C, block comment statements are bracketed by /* and */ symbols. C++-style line comments start by //, two forward slashes, and are usually also supported. Get into the habit of writing helpful comment statements in your code.
  • Each statement in C must end with a semicolon (;)
  • return is another standard statement in C. It basically tells C that you're done in this part of the code. Since it's the only part of the code, it tells C where to finish.