quarts.c: A first program in C
As a first program in C, consider the following code that converts a number of quarts to liters. Commentary after the program explains each element of this program. A subsequent section explains how this program may be run.
/* A simple program to convert a number of quarts to liters
* Version 1: global variables only
* Author: Henry Walker
*/
#include /* reference to standard I/O library */
const double QUARTS_PER_LITER = 1.056710; /* define constant conversion factor */
int
main (void) /* beginning of main program */
{
int quarts; /* variable declarations */
double liters; /* double = real */
printf ("This program converts a number of quarts to liters\n");
/* write opening statement */
quarts = 2; /* specify the number of quarts as 2 */
liters = quarts / QUARTS_PER_LITER; /* arithmetic, assignment */
printf ("%d quarts = %lf liters\n", quarts, liters);
/* write text and new line */
return 0; /* the program ran without errors */
} // main
Commentary on the quarts.c program
-
Comments in C begin anywhere with the
symbols
/*, continuing until the symbols*/, on the same or later lines. -
C makes use of libraries for many common operations, including
the
stdiolibrary for input (reading from the keyboard) and output (printing). The statement
instructs the machine how to use the#include <stdio.h>stdiooperations by declaring the signatures of these functions in your program (similar to therequirestatements you used in Scheme). -
Each C program contains a driver function/procedure, called
main. Here, main uses no input parameters (hence the parentheses withvoidbetween them followingmain). In standard C, themainfunction/procedure returns an integer as an error code (hence theintbeforemain). When the program runs normally, without error, the integer 0 is usually returned. -
Variables may be declared
globally
orlocally
within a C function. Here,quartsandlitersare declared locally as integer and real variables, respectively. The variableQUARTS_PER_LITERis declared globally (outside ofmain), and is also declared as a constant withconst, which essentially means it cannot be reassigned a new value. The termdoublespecifies a real number, stored using double precision. (The termfloatmay be used for single precision, real numbers.) -
Braces
{and}are used in C to mark the beginning and ending of blocks. In this case, the braces indicate the statements for themainprocedure. -
Semicolons (
;) are used to terminate every statement in C. -
The equal sign (
=) is used for assignment. (We will see later that==, is used as a comparison operator.) -
Arithmetic operations
include
+,-,*, and/for addition, subtraction, multiplication, and division. For integers, the division operation/yields the integer quotient, while the modulus operation%gives the remainder. -
printfis used for output. The first parameter is a string, which indicates how the output will be formatted.-
When printing text only, as in the first output line in this
program, the text of the string is enclosed in double
quotes
" ", and the characters are printed exactly as given. -
Within a format string, some symbols are used for special
symbols. For example,
\n, a new-line character\t, a tab character\", a double quote character\\, a backslash character itself
-
When printing the value of a variable, the format string
for
printfgives the type of data to be displayed:"%d"for a (decimal) integer"%f"for a (floating point) real number"%lf"for a double precision (long) real number"%c"for a (single) character"%s"for a character string
-
When printing text only, as in the first output line in this
program, the text of the string is enclosed in double
quotes
Developing and Running a C Program
Authoring Programs
To prepare a program in C, one uses a text editor, such as emacs or vi. Do not use a word processing package, such as LibreOffice, Microsoft Word, or Apple Pages because these packages insert extensive formatting and font information that will confuse the computer as it tries to follow the instructions in your program.
Preparing Programs for Execution
Once the program has been written with the editor and saved, the program must be translated from C to machine language. (In Scheme, such work is done behind the scenes, but in C the translation must be made explicit.) The translation actually consists of four separate steps: preprocessing, compilation, assembly, and linking. The entire process is usually referred to simply as compiling. Below we briefly explain each of these processes. They may not have much significance now, but as we unpack more features or details of the language, their importance and salience should increase.
- Preprocess
-
Your program is first treated by a preprocessor, which
may add definitions and otherwise modify the text of your
program. The C preprocesor responds to directives
beginning with the so-called pound symbol (
#); the#include <stdio.h>(spoken as "pound include") at the beginning ofquarts.cis a common example. This directive adds the header file, which contains function signatures (more on both of those in a few weeks), to your program. For the most part, the preprocessor directives we use will be straightforward. However, because they modify your program before the compiler (discussed next) sees it, bugs in your directives can sometimes be difficult to diagnose. - Compile
- After the preprocessor runs, another program called a compiler looks at your program text and translates it from the "high" level C language to a lower-level language called assembly, which is a human-readable sequence of commands the computer accepts. The compiler will often be the part of the entire build process that produces errors and warnings about your program.
- Assemble
- Another translation program called an assembler handles the straightforward task of changing the low-level human-readable instructions into machine code, which is an object that can be directly loaded and executed by the computer.
- Link
- As a final step, a program called a linker connects all of your machine objects with any library code your program relies on, building the final executable program.
Fortunately, you now rarely need to invoke these steps
separately. The common compilers for C, the GNU C
compiler gcc and the LLVM compiler clang,
integrate all four of these steps for you.
The following interaction in a terminal window shows a sample
session, including writing, translating, and
running quarts.c.
emacs quarts.c & clang -o quarts quarts.c ./quarts
This program converts a number of quarts to liters 2 quarts = 1.892667 liters
In this example, emacs quarts.c & starts the
emacs editor to prepare a new program called
quarts.c. The ampersand (&) allows
editing to take place while the terminal window can still be used for
other activities.
To compile the program, the line clang -o quarts quarts.c
uses clang with the program we have edited
(quarts.c). The directive -o quarts
indicates we want the linker to place our translated program in an
output file called quarts.
Warning: Be sure the name of the output file
(quarts) is different from the name of your original
program (quarts.c). If you use the same name for
both, your original program will be overwritten and lost!
You run the translated program by typing ./quarts .
As with any command in a terminal window, the prefix ./
indicates that this program may be found in your current directory.
