First Programs

In this first post we will look at a few very basic programs.

#include <stdio.h>

int main(void){

  /*
   * A very basic program.
   */

  printf("Three pounds of flax.");

  return 0;
}

We should try to get into the habit of documenting our programs with comments. Comments are placed between /* and */, as the compiler will ignore any code following /* until a matching */ is found. Comments can span multiple lines, and can be placed wherever we want.

#include <stdio.h>

int main(void){

 /*
  *print output to stdout
  */ 
 printf("Why is a raven like a writing desk?");

 /*
  * return control to the operating system
  */ 
 return 0;

}

The return statement in the program above returns control to the operating system.

The # symbol in the first line of the program indicates that this line is a preprocessing directive. A preprocessing directive is a special instruction to the compiler to do something before compiling the source code. A very common preprocessing directive is to include a header file; in this example we are including the stdio.h header file. A header file contains a set of code for the program to use There is a standard library of header files that all compilers should have, stdio.h is one of these. All header files in C have the .h file extension.

#include <stdio.h>
/*
 *preprocessor directive
 * /

/*
 * begin the program
 * with the main() function
 */
int main(void){

 /*
  * display output using 
  * printf() function
  */
 printf("Photons be free!");

 /*
  * end execution of the main() function
  */
 return 0; 

}

A function is a named block of code. A function in C is delimited by curly braces. Every C program consists of one or more functions, one of which must be called main(), this is the function that controls the program, and from which other functions are called.

Most functions end with a return statement. A return statement sends a value back to the function that called it. In the case of main(), the function returns 0, this return value indicates that the program terminated normally; a nonzero value returned to the operating system would indicate that there was a problem.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s