The C programming language has been around since 1972 and is still widely used today. That is because it is a very efficient and portable language which can provide high levels of performance on most hardware architectures. It compiles into native executables and may, therefore, be found in everything from a Linux workstation to an embedded processor in a mobile phone. However, the code is low level and easy to understand. It is, for these reasons, a suitable language for programmers at all levels from beginner to seasoned professional.
The Components of a C Program
Any C program consists of 4 components:
- Comments. Comments are ignored by the program compiler but are essential to the programmer. These provide important guides both to the programmer themselves and to other programmers who may need to work on the project. One of the great arts of programming is to produce enough comments to aid in the application development but not so many that they become irrelevant;
- Include statements. A C programmer does not have to program everything from scratch. They may include functionality from other programs that they have written or even written by other programmers;
- Prototype and variable declarations. Each function and its variables have to be declared before they can be used within the application;
- Functions. The body of the program. This is where the programmer creates the functionality of the application.
Each of these concepts can be better understood by a new programmer if they are used in a real application - the obligatory "Hello World" program
The C "Hello World" Program
The simplest possible C program is one that sends a simple output (such as "Hello, World") to the screen. However, before creating any functionality, the first job is to add a comment that explains who wrote the program as well as when and why. Each comment starts with /* and ends with */:
/* hello.c
Author: Mark Alexander Bain:
Created: 2010-08-07
This program produces a simple output
*/
#include /* Writing to the screen is not necessarily that easy to accomplish. However, the programmer need not concern themselves about the technicalities. The stdio.h defines all of the functionality that they will require */
void hello(void); /*Declare a function to be used. This will not return anything to the program (but will produce an output to the screen)*/
/* The main() function. This is automatically run by the program. */
int main (void ) { /* The function requires not input, but will return an integer */
hello(); /* Call the function that will send text to the screen*/
}
/* The "hello world" function */
void hello(void)
{
puts ("Hello, World");
}
If this is saved as "hello.c" then the programmer can compile it:
gcc -o hello hello.c
This will create an executable named "hello" which, when run, will write a simple "Hello, World" to the screen.