| I l @ ve RuBoard |
We'll take two
#include <stdio.h> include another file
This line
int main(void) a function name
C programs consist of one or more functions, the basic modules of a C program. This program consists of one function called main . The parentheses identify main() as a function name. The int indicates that the main() function returns an integer, and the void indicates that main() doesn't take any arguments. These are matters we'll go into later. Right now, just accept the int and void as part of the standard ANSI C way for defining main() . (If you have a pre-ANSI C compiler, omit the void .)
/* a simple program */ a comment
The symbols /* and */ enclose comments, remarks that help clarify a program. They are intended for the reader only and are ignored by the compiler.
{ beginning of the body of the function
This opening brace marks the start of the statements that make up the function. The function definition is ended with a closing
int num; a declaration statement
This statement announces that you are using a variable called num and that num will be an int (integer) type.
num = 1; an assignment statement
The statement
num = 1;
printf("I am a simple "); a print statement
The first printf statement displays the phrase I am a simple on your screen, leaving the cursor on the same line.
printf("computer.\n"); another print statement
The
printf ("My favorite number is %d because it is first.\n", num);
The last printf statement prints the value of num (which is 1 ) embedded in the phrase in quotes. The %d instructs the computer where and in what form to print the value of num .
return 0; a return statement
A C function can furnish, or return, a number to the agency that used it. For the present, just regard this line as part of the ANSI C requirement for a properly written main() function.
} the end
As
Now take a closer look at the program.
#include <stdio.h>
The effect of
#include <stdio.h>
is the same as though you had typed the entire contents of the
stdio.h
file into your file at the point where the
#include
line appears. Include files provide a
The
stdio.h
file is supplied as part of all C compiler packages. It contains information about input and output functions, such as
printf()
, for the compiler to use. The name stands for
st
an
d
ard
i
nput/
o
utput
h
eader. C programmers call a collection of information that goes at the top of a file a
header
, and C
Some programs need to include stdio.h ; some don't. The documentation for a particular C implementation should include a description of the functions in the C library. These function descriptions identify which header files are needed. For example, the description for printf() says to use stdio.h . Omitting the proper header file might not affect a particular program, but it is best not to rely on that. Each time this book uses library functions, it will use the include files specified by the ANSI standard for those functions. Because the compiler uses the information in the stdio.h to build a program, any information that the compiler does not use does not become part of the program. Therefore, including an unnecessary file does not make the final program any longer.
The #include statement is an example of a C preprocessor directive . In general, C compilers perform some preparatory work on source code before compiling; this is termed preprocessing .
Why Input and Output Are Not Built InPerhaps you are wondering why something as basic as input and output information isn't included automatically. One answer is that not all programs use this I/O (input/output) package, and part of the C philosophy is to avoid carrying unnecessary weight. Incidentally, the #include line is not even a C language statement! The # symbol in column 1 identifies the line as one to be handled by the C preprocessor before the compiler takes over. You will encounter more examples of preprocessor instructions later. |
int main(void)
True,
main
is a rather plain name, but it is the only choice available. A C program always begins execution with the function called
main()
. You are free to choose
The int is the main() function's return type. That means that the kind of value main() can return is an integer. Return where? To the operating system ”we'll come back to this question in Chapter 6, "C Control Statements: Looping."
The parentheses following a function name
Pre-ANSI C programs usually omitted the int and the void :
main()
ANSI C also accepts this form. It interprets the empty parentheses to mean that you decline to say anything about the kind of information
main()
requires. Omitting the
int
has no effect, for C (both K&R and ANSI) assumes that a function has an
int
return type unless you state
/* a simple program */
Using comments makes it easier for someone (including yourself) to understand your program. One nice feature of C comments is that they can be placed
/* This is a C comment. */ /* This comment is spread over two lines. */ /* You can do this, too. */ /* But this is invalid because there is no end marker.
C++ has a second comment syntax that many C compilers have adopted. Also, the C9X committee proposes recognizing this common practice by adding the new syntax to the next version of the ANSI standard. The new style uses the symbols // to create comments that are confined to a single line:
// Here is a comment confined to one line. int borg; // Such comments can go here, too.
Because the end of the line marks the end of the comment, this style needs comment markers just at the beginning of the comment.
{
...
}
Braces mark the beginning as well as the end of the body of a function. Their presence is mandatory. Only braces { } work for this purpose, not parentheses ( ) and not brackets [ ] .
Braces can also be used to gather statements within a function into a unit or block. If you are familiar with Pascal, ADA, Modula-2, or Algol, you will recognize the braces as being similar to begin and end in those languages.
int num;
The
declaration statement
is one of C's most important features. This particular example declares two things. First, somewhere in the function, you have a
variable
called
num
. Second, the
int
proclaims
num
as an integer, that is, a number without a decimal point or
The word int is a C keyword identifying one of the basic C data types. Keywords are the words used to express a language, and you can't usurp them for other purposes. For instance, you can't use int as the name of a function or a variable.
In C,
all
variables should be declared before they are used. This means that you have to provide lists of all the
At this point, you probably have three questions. First, what are data types? Second, what choices do you have in selecting a name? Third, why do you have to declare variables at all? Let's look at some answers.
C deals with several kinds (or types) of data: integers,
We suggest that you use meaningful names for variables. The number of characters you can use varies among implementations, but the lower limit is at least eight characters. The ANSI C standard calls for up to 31 characters, except for external identifiers (see Chapter 13, "Storage Classes and Program Development" ), for which only six characters need to be recognized. (C9X raises the minimum values to 63 characters and 31 characters, respectively.) Actually, you can use more than the maximum number of characters, but the compiler won't pay attention to the extra characters. Therefore, on a system with an eight-character limit,
| Valid Names | Invalid Names |
|---|---|
| wiggles | $Z]** |
| cat1 | 1cat |
| Hot_Tub | Hot-Tub |
| _kcab | don't |
Operating systems and compilers often use identifiers with one or two initial underscore characters, so it is better to avoid that usage yourself.
C names are case sensitive, meaning an uppercase letter is considered distinct from the corresponding lowercase letter. Therefore, socks is different from Socks or SOCKS .
Putting all the variables in one place makes it easier for a reader to grasp what the program is about. This is particularly true if you give your variables meaningful names (such as taxrate instead of r ). If the name doesn't suffice, use comments to explain what the variables represent. Documenting a program in this manner is one of the basic techniques of good programming.
Thinking about what to put into the variable declaration section encourages you to do some planning before plunging into writing a program. What information does the program need to get started? What exactly do I want the program to produce as output? What is the best way to represent the data?
Declaring variables helps prevent one of programming's more subtle and hard-to-find
RADIUS1 = 20.4;
and that elsewhere in the program you
CIRCUM = 6.28 * RADIUSl;
You unwittingly
Your C program will not compile if you don't declare your variables. If the
By the way, if you find that your compiler allows you to declare variables anywhere in a block and not just at the beginning, the compiler may be a C++ mode, for C++ does allow that behavior. (See Appendix G, "Answers to Review Questions." )
num = 1;
The assignment statement is one of the basic operations in C. This particular example means "assign the value 1 to the variable num ." The earlier int num; line allotted computer space for the variable num , and the assignment line gives it its value. You can assign num a different value later on, if you want; that is why num is termed a variable. Note that the assignment statement assigns a value from the right side to the left side. Also, the statement is completed with a semicolon, as shown in Figure 2.2.
printf ("I am a simple ");
printf ("computer.\n");
printf ("My favorite number is %d because it is first.\n",num);
These lines all use a standard C function called
printf()
. The parentheses signify that
printf
is a function name. The material
This first
printf()
line is an example of how you
call
or
invoke
a function in C. You need type only the name of the function, placing the desired argument(s) within the parentheses. When the program
What about this next
printf()
line? It has the characters
\n
included in the quotes, and they didn't get printed! What's going on? The
\n
symbol means to start a new line. The
\n
combination (typed as two characters) represents a single character called the
newline character
. Its meaning is "start a new line at the far left margin." In other words, printing the newline character
The newline character is an example of an
escape sequence
. An escape sequence is used to represent difficult- or
Well, that explains why the three printf() statements produced only two lines: The first print instruction didn't have a newline character in it, but the second and third did.
The final
printf()
line
My favorite number is 1 because it is first.
Aha! The digit
1
was substituted for the symbol
PRINT "My favorite number is "; num; " because it is first."
The C version does a little more than this, actually. The
%
alerts the program that a variable is to be printed at that location, and the
d
tells it to print the variable as a decimal (base 10) integer. The
printf()
function allows several choices for the format of printed variables, including hexadecimal (base 16) integers and
return 0;
The int in int main(void) means that the main() function is supposed to return an integer. The ANSI C standard requires that main() behave that way. C functions that return values do so with a return statement, which consists of the keyword return followed by the returned value followed by a semicolon. If you leave out the return statement for main() , most compilers will chide you for the omission, but still compile the program. At this point, you can regard the return statement in main() as something required for logical consistency, but it has a practical use with some operating systems, including DOS and UNIX. I'll return to that topic in Chapter 11, "Character Strings and String Functions."
| I l @ ve RuBoard |