Preprocessing Directives
Look at the following line of code:
#include <stdio.h> // This is a preprocessor
directive
This is not strictly part of the
executable program, but it is essential in this case—in fact, the program won’t
work without it. The symbol # indicates this is a preprocessing directive, which is an instruction to your compiler
to do something before compiling the source code. The compiler handles these
directives during an initial preprocessing phase before the compilation process
starts. There are quite a few preprocessing directives, and there are usually
some at the beginning of the program source file, but they can be anywhere.
In this case, the compiler is
instructed to “include” in your program the contents of the file with the name
stdio.h. This file is called a header
file, because it’s usually included at the head of a program source file.
In this case the header file defines information about some of the functions
that are provided by the standard C library but, in general, header files
specify information that the compiler uses to integrate any predefined
functions or other global objects within a program. You’ll be creating your own
header files for use with your programs. In this case, because you’re using the
printf() function from the standard library, you have to include the stdio.h
header file. This is because stdio.h contains the information that the compiler
needs to understand what printf() means, as well as other functions that deal
with input and output. As such, its name, stdio, is short for standard input/output. All header files in C have file names with
the extension .h. You’ll use other standard header files later in the book.
■ Note
header file names are case sensitive on
some systems, so you should always write them in lowercase in #include directives.
Every C compiler
that conforms to the C11 standard will have a set of standard header files
supplied with it. These header files primarily contain declarations relating to
standard library functions and macros that are available with C. Although all C
compilers that conform with the standard will support the same basic set of
capabilities and will have the same set of mandatory standard header files
available, there are standard header files that are optional, and in some cases
extra library functions can be provided with a particular compiler that may not
be available with other compilers that will typically provide functionality
specific to the type of computer on which the compiler runs.
■ Note
all the standard header files are listed
in appendix e.
Defining the main() Function
The next five statements define the
function main():
int
main(void) //
This identifies the function main() { // This
marks the beginning of main()
printf("Beware the Ides of March!"); // This line outputs a quotation
return 0;
// This returns control to the operating system
} // This
marks the end of main()
A function is just a named block of code between braces that carries
out some specific set of operations. Every C program consists of one or more
functions, and every C program must contain a function called main()—the reason
being that a program always starts execution from the beginning of this function.
So imagine that you’ve created, compiled, and linked a file called
progname.exe. When you execute this program, the operating system executes the
function main() for the program.
The first line of the definition for
the function main() is as follows:
int main(void) // This identifies the function
main()
This defines the start of main().
Notice that there is no semicolon at
the end of the line. The first line identifying this as the function main() has
the word int at the beginning. What appears here defines the type of value to
be returned by the function, and the word int signifies that main() returns an
integer value. The integer value that is returned when the execution of main()
ends represents a code that is returned to the operating system that indicates
the program state. You end execution of main() and specify the value to be
returned in this statement:
return 0; // This returns control to
the operating system
This is a return statement that ends
execution of main() and returns the value 0 to the operating system. You return
a zero value from main() to indicate that the program terminated normally; a
nonzero value would indicate an abnormal return, which means things did not
proceed as they should have when the program ended.
??= converts to # |
??( converts to [ |
??)
converts to ] |
??/ converts to \ |
??< converts to { |
??>
converts to } |
??' converts to ^ |
??! converts to | |
??-
converts to ~ |
Keywords
In C, a keyword is a word with special significance, so you must not use
keywords for any other purpose in your program. For this reason, keywords are
also referred to as reserved words.
In the preceding example, int is a keyword and void and return are also
keywords. C has several keywords, and you’ll become familiar with more of them
as you learn more of the language. You’ll find a complete list of C keywords in
Appendix C.
The Body of a Function
The general structure of the
function main() is illustrated in Figure 1-2.
Figure 1-2. Structure of the function main()
The function body is the bit between
the opening and closing braces that follows the line where the function name
appears. The function body contains all the statements that define what the
function does. The example’s main() function has a very simple function body
consisting of just two statements:
{ // This
marks the beginning of main()
printf("Beware the Ides of March!"); // This line outputs a quotation
return 0;
// This returns control to the operating system
} // This
marks the end of main()
Every function must have a body,
although the body can be empty and just consist of the opening and closing
braces without any statements between them. In this case, the function will do
nothing.
You may wonder what use a function
that does nothing is? Actually, this can be very useful when you’re developing
a program that will have many functions. You can declare the set of (empty)
functions that you think you’ll need to write to solve the problem at hand,
which should give you an idea of the programming that needs to be done, and
then gradually create the program code for each function. This technique helps
you to build your program in a logical and incremental manner.
■ Note You can see that i’ve aligned the braces one below the other in
program 1.3 and indented the statements between them. i’ve done this to make it
clear where the block of statements that the braces enclose starts and
finishes. Statements between braces are usually indented by a fixed
amount—usually two or more spaces—so that the braces stand out. this is good
programming style, because it allows the statements within a block to be
readily identified.
There are other styles for arranging
braces in code. For example:
int main(void) {
printf("Beware the Ides of March!"); // This line outputs a quotation
return 0; }
■ Tip
With whatever style you use to arrange
your source code, the most important thing is to apply it consistently.
Outputting Information
The body of the main() function in
the example includes a statement that calls the printf() function:
printf("Beware the Ides of
March!"); // This line outputs
a quotation
As I’ve said, printf() is a standard
library function, and it outputs information to the command line (actually the standard output stream, which is the
command line by default) based on what appears between the parentheses that
immediately follow the function name. In this case, the call to the function
displays the simple piece of Shakespearean advice that appears between the
double quotes; a string of characters between double quotes like this is called
a string literal. Notice that this
line does end with a semicolon.
Function Arguments
Items enclosed between the
parentheses following a function name, as with the printf() function in the
previous statement, are called arguments,
and they specify data that are to be passed to the function. When there is more
than one argument to a function, they must be separated by commas.
In the previous example the argument
to the function is the text string between double quotes. If you don’t like the
quotation that is specified here, you could display something else by simply
including your own choice of words enclosed within double quotes inside the
parentheses. For instance, you might prefer a line from Macbeth:
printf("Out, damned Spot! Out I
say!");
Try using this in the example. When
you’ve modified the source code, you need to compile and link the program again
before executing it.
■ Note as with all executable statements in C (as opposed to defining or
directive statements) the printf() line must have a semicolon at the end. a very common error when you
first start programming in C is to forget the semicolon.
Control Characters
You could alter the program to
display two sentences on separate lines using a single printf() statement. Try
typing in the following code:
// Program 1.4 Another Simple C
Program - Displaying a Quotation
#include <stdio.h>
int main(void)
{
printf("My formula for success?\nRise early, work late, strike
oil.\n");
return 0;
}
The output from this program looks
like this:
My formula
for success? Rise early, work late, strike oil.
Look at the
printf() statement. After the first sentence and at the end of the text, you’ve
inserted the characters \n. The combination \n is another escape sequence that
represents a newline character. This causes the output cursor to move to the
next line, so any subsequent output will start on a new line.
The backslash (\) is always of
special significance in a text string because it indicates the start of an
escape sequence. The character following the backslash indicates what character
the escape sequence represents. In the case of \n, it’s n for newline, but
there are plenty of other possibilities. Because a backslash itself is of special
significance, you need a way to specify a backslash in a text string. To do
this, you simply use two backslashes: \\. Type in the following program:
// Program 1.5 Another Simple C
Program - Displaying Great Quotations
#include <stdio.h>
int main(void)
{
printf("\"It is a wise father that knows his own
child.\"\nShakespeare\n");
return 0;
}
The output displays the following
text:
"It is
a wise father that knows his own child."
Shakespeare
The double
quotes are output because you use escape sequences for them in the string.
Shakespeare appears on the next line because there is a \n escape sequence
following the \".
4
programming
in C
You can use the \a escape sequence
in an output string to sound a beep to signal something interesting or
important. Enter and run the following program:
// Program 1.6 A Simple C Program –
Important
#include <stdio.h>
int main(void)
{
printf("Be careful!!\n\a");
return 0; }
The output of this program is sound
and vision. Listen closely and you should hear the beep through the speaker in
your computer.
Be careful!!
The \a sequence represents the
“bell” character. Table 1-1 shows all the escape sequences that
you can use.
Table 1-1. Escape Sequences
Escape sequence Description
\n Represents
a newline character
\r Represents
a carriage return
\b Represents
a backspace
\f Represents
a form-feed character
\t Represents
a horizontal tab
\v Represents
a vertical tab
\a Inserts
a bell (alert) character
\? Inserts
a question mark (?)
\" Inserts
a double quote (")
\' Inserts
a single quote (')
\\ Inserts
a backslash (\)
Try displaying different lines of text on the screen and
alter the spacing within that text. You can put words on different lines using
\n, and you can use \t to space the text. You’ll get a lot more practice with
these as you progress through the book.
Trigraph Sequences
In general you can use a question
mark directly in a string. The \? escape sequence only exists because there are
nine special sequences of characters called trigraph sequences that are
three-characters sequences for representing each of the characters #, [,], \,
^, ~, \, {, and }:
These are there for when it is
necessary to write C code in the International Organization for
Standardization ISO invariant code set,
which does not have these characters. This is unlikely to apply to you. You can
completely forget about all this unless you want to write a statement such as:
printf("What??!\n");
The output produced by this
statement will be:
What|
The trigraph
??! will be converted to |. To get the output you intended, you need to write
the statement as:
printf("What?\?!\n");
Now the trigraph sequence does not
appear because the second question mark is specified by its escape sequence.
Your compiler may well issue a warning when you use a trigraph sequence because
usually it is unintended.
The
Preprocessor
In the example I explained how you
use a preprocessing directive to include the contents of a header file into
your source file. The preprocessing phase of compilation can do much more than
this. As well as directives, your source file can contain macros. A macro is an instruction to the
preprocessor to add to or modify the C statements in the program. A macro can
be something as simple as defining a symbol, such as INCHES_PER_FOOT to be
replaced by 12 wherever the symbol
appears. The directive to do this is:
#define INCHES_PER_FOOT 12
With this directive at the beginning
of your source file, wherever INCHES_PER_FOOT appears in the code, it will be
replaced by 12. For example:
printf("There
are %d inches in a foot.\n", INCHES_PER_FOOT);
After preprocessing, this statement
will be:
printf("There are %d inches in
a foot.\n", 12);
INCHES_PER_FOOT no longer appears
because the symbol has been replaced by the string specified in the #define
directive. This will happen for every instance of the symbol in the source file.
A macro can also be quite complicated, with significant amounts of code being added to a source file depending on specified conditions. I won’t go into this further here. I will discuss preprocessor macros in detail in Chapter 13. You will meet some mac
0 comments:
Post a Comment