Next: Programming Elements
Up: Physics 2101 - Scientific
Previous: Inheritance
Contents
Index
A C Program
Writing a program in C requires one additional step
compared to that of Perl:
- Create a text file with the commands you
wish to carry out,
- Compile this program to make an executable,
- Run the executable.
A simple C program that just prints out something
to the terminal screen is
#include <stdio.h>
/* This is a comment */
int main(void) {
printf("Hello\n");
return 0;
}
After creating this file, save it as, for example, hello.c,
and compile it as
C:\> bcc32 hello.c
C:\> hello
on Windows (using the Borland bcc32 compiler), or on Unix as
bash$ gcc -o hello hello.c
bash$ ./hello
The first stage of compiling the file creates the executable -
on Windows, the name of the executable is, by default,
hello.exe, while on Unix one specifies it with the
-o option. The second stage runs this executable.
There are some notable differences between this file
and the equivalent one as a Perl script:
- the notation for comments - in C, things between
/* and */ are comments, even spanning multiple lines;
- the presence of the line #include <stdio.h> - this
pulls in the header file stdio.h (standard input
and output), which contains some common definitions (prototypes)
for various functions;
- the presence of an int main(void) { ... } - this
in the ``main'' routine, and contains the code to be run; the
int signifies that this routine must return an integer
(typically 0 if the program runs successfully, and non-zero
if an error of some sort is encoutered);
- the use of printf (``print format''), rather than print,
in printing to the terminal screen.
Next: Programming Elements
Up: Physics 2101 - Scientific
Previous: Inheritance
Contents
Index