Next: September 13
Up: September 11
Previous: C differs from Java
Sample C program
/* add.c
* a simple C program
*/
#include <stdio.h>
#define LAST 10
int main()
{
int i, sum = 0;
for ( i = 1; i <= LAST; i++ ) {
sum += i;
} /*-for-*/
printf("sum = %d\n", sum);
return 0;
}
The main parts are:
- preprocessor directives (notable by the
#
character and the
lack of semicolons)
- global variable declarations
- function declarations
- int main()
- function definitions
Here's a brief description of those parts:
- Comments:
- These start with
/*
and continue, ignoring
newlines, until the next */
. Notice that this means there is
no nesting of comments. We adhere to ANSI-C standard (until C99
becomes more ubiquitous), so you cannot assume that //
comments until the end of a line will work. It may turn out that
some compilers accept these, but you cannot assume that all
compilers (particularly the one used by the marking TA) will.
- #include directives:
- includes declarations of functions
from header files for standard libraries. For example,
#include <stdio.h> includes declarations of
functions for the standard library that are useful for
input/output. Note the distinct absence of semicolon
- #define directives:
- Performs textual replacement,
which is useful to define constants. For example, this is legal C:
#include <stdio.h>
#define BEGIN {
#define END }
int main()
BEGIN
printf("Hello World!\n");
return 0;
END
- int main():
- An executable program must have a
main method, which is what's called when the program is
executed. int indicates that this function returns an
integer value to the shell where it is executed. In this course we
will normally return 0.
Next: September 13
Up: September 11
Previous: C differs from Java
Danny Heap
2002-12-16