Sei sulla pagina 1di 23

Welcome to Sams' Teach Yourself C in 21 Days!

This chapter starts you toward becoming


a proficient C programmer. Today you will learn
Why C is the best choice among programming languages
The steps in the program development cycle
How to write, compile, and run your first C program
About error messages generated by the compiler and linker
A Brief History of the C Language
You might be wondering about the origin of the C language and where it got its name. C
was created by ennis !itchie at the "ell Telephone #aboratories in $%&'. The language
wasn(t created for the fun of it, but for a specific purpose) to design the *+,- operating
system .which is used on many computers/. 0rom the beginning, C was intended to be
useful11to allow busy programmers to get things done.
"ecause C is such a powerful and fle2ible language, its use 3uickly spread beyond "ell
#abs. 4rogrammers everywhere began using it to write all sorts of programs. 5oon,
however, different organi6ations began utili6ing their own versions of C, and subtle
differences between implementations started to cause programmers headaches. ,n
response to this problem, the American +ational 5tandards ,nstitute .A+5,/ formed a
committee in $%78 to establish a standard definition of C, which became known as A+5,
5tandard C. With few e2ceptions, every modern C compiler has the ability to adhere to
this standard.
+ow, what about the name9 The C language is so named because its predecessor was
called ". The " language was developed by :en Thompson of "ell #abs. You should be
able to guess why it was called ".
Why Use C?
,n today(s world of computer programming, there are many high1level languages to
choose from, such as C, 4ascal, "A5,C, and ;ava. These are all e2cellent languages
suited for most programming tasks. <ven so, there are several reasons why many
computer professionals feel that C is at the top of the list)
C is a powerful and fle2ible language. What you can accomplish with C is limited
only by your imagination. The language itself places no constraints on you. C is
used for pro=ects as diverse as operating systems, word processors, graphics,
spreadsheets, and even compilers for other languages.
C is a popular language preferred by professional programmers. As a result, a
wide variety of C compilers and helpful accessories are available.
C is a portable language. Portable means that a C program written for one
computer system .an ,"> 4C, for e2ample/ can be compiled and run on another
system .a <C ?A- system, perhaps/ with little or no modification. 4ortability is
enhanced by the A+5, standard for C, the set of rules for C compilers.
C is a language of few words, containing only a handful of terms, called
keywords, which serve as the base on which the language(s functionality is built.
You might think that a language with more keywords .sometimes called resered
words/ would be more powerful. This isn(t true. As you program with C, you will
find that it can be programmed to do any task.
C is modular. C code can .and should/ be written in routines called functions.
These functions can be reused in other applications or programs. "y passing
pieces of information to the functions, you can create useful, reusable code.
As these features show, C is an e2cellent choice for your first programming language.
What about C@@9 You might have heard about C@@ and the programming techni3ue
called ob!ect"oriented #ro$rammin$. 4erhaps you(re wondering what the differences are
between C and C@@ and whether you should be teaching yourself C@@ instead of C.
+ot to worryA C@@ is a superset of C, which means that C@@ contains everything C does,
plus new additions for ob=ect1oriented programming. ,f you do go on to learn C@@,
almost everything you learn about C will still apply to the C@@ superset. ,n learning C,
you are not only learning one of today(s most powerful and popular programming
languages, but you are also preparing yourself for ob=ect1oriented programming.
Another language that has gotten lots of attention is ;ava. ;ava, like C@@, is based on C.
,f later you decide to learn ;ava, you will find that almost everything you learned about C
can be applied.
Preparing to Program
You should take certain steps when you(re solving a problem. 0irst, you must define the
problem. ,f you don(t know what the problem is, you can(t find a solutionA Bnce you
know what the problem is, you can devise a plan to fi2 it. Bnce you have a plan, you can
usually implement it. Bnce the plan is implemented, you must test the results to see
whether the problem is solved. This same logic can be applied to many other areas,
including programming.
When creating a program in C .or for that matter, a computer program in any language/,
you should follow a similar se3uence of steps)
1. etermine the ob=ective.s/ of the program.
2. etermine the methods you want to use in writing the program.
3. Create the program to solve the problem.
4. !un the program to see the results.
An e2ample of an ob=ective .see step $/ might be to write a word processor or database
program. A much simpler ob=ective is to display your name on the screen. ,f you didn(t
have an ob=ective, you wouldn(t be writing a program, so you already have the first step
done.
The second step is to determine the method you want to use to write the program. o you
need a computer program to solve the problem9 What information needs to be tracked9
What formulas will be used9 uring this step, you should try to determine what you need
to know and in what order the solution should be implemented.
As an e2ample, assume that someone asks you to write a program to determine the area
inside a circle. 5tep $ is complete, because you know your ob=ective) determine the area
inside a circle. 5tep ' is to determine what you need to know to ascertain the area. ,n this
e2ample, assume that the user of the program will provide the radius of the circle.
:nowing this, you can apply the formula pr
'
to obtain the answer. +ow you have the
pieces you need, so you can continue to steps 8 and C, which are called the 4rogram
evelopment Cycle.
The Program e!e"opment Cy#"e
The 4rogram evelopment Cycle has its own steps. ,n the first step, you use an editor to
create a disk file containing your source code. ,n the second step, you compile the source
code to create an ob=ect file. ,n the third step, you link the compiled code to create an
e2ecutable file. The fourth step is to run the program to see whether it works as originally
planned.
Creating the $our#e Co%e
Source code is a series of statements or commands that are used to instruct the computer
to perform your desired tasks. As mentioned, the first step in the 4rogram evelopment
Cycle is to enter source code into an editor. 0or e2ample, here is a line of C source code)
printf("Hello, Mom!");
This statement instructs the computer to display the message Hello, >omA on1screen.
.0or now, don(t worry about how this statement works./
Using an &%itor
>ost compilers come with a built1in editor that can be used to enter source codeD
however, some don(t. Consult your compiler manuals to see whether your compiler came
with an editor. ,f it didn(t, many alternative editors are available.
>ost computer systems include a program that can be used as an editor. ,f you(re using a
*+,- system, you can use such editors as ed, e2, edit, emacs, or vi. ,f you(re using
>icrosoft Windows, +otepad is available. ,f you(re using >5EB5 F.G or later, you can
use <dit. ,f you(re using a version of B5 before F.G, you can use <dlin. ,f you(re using
4CEB5 H.G or later, you can use <. ,f you(re using B5E', you can use the < and <4>
editors.
>ost word processors use special codes to format their documents. These codes can(t be
read correctly by other programs. The American 5tandard Code for ,nformation
,nterchange .A5C,,/ has specified a standard te2t format that nearly any program,
including C, can use. >any word processors, such as Word4erfect, Ami4ro, Word,
Word4ad, and Word5tar, are capable of saving source files in A5C,, form .as a te2t file
rather than a document file/. When you want to save a word processor(s file as an A5C,,
file, select the A5C,, or te2t option when saving.
,f none of these editors is what you want to use, you can always buy a different editor.
There are packages, both commercial and shareware, that have been designed specifically
for entering source code.
'(T&) To find alternative editors, you can check your local computer store or computer
mail1order catalogs. Another place to look is in the ads in computer programming
maga6ines.
When you save a source file, you must give it a name. The name should describe what the
program does. ,n addition, when you save C program source files, give the file a .C
e2tension. Although you could give your source file any name and e2tension, .C is
recogni6ed as the appropriate e2tension to use.
Compi"ing the $our#e Co%e
Although you might be able to understand C source code .at least, after reading this book
you will be able to/, your computer can(t. A computer re3uires digital, or binary,
instructions in what is called machine lan$ua$e. "efore your C program can run on a
computer, it must be translated from source code to machine language. This translation,
the second step in program development, is performed by a program called a com#iler.
The compiler takes your source code file as input and produces a disk file containing the
machine language instructions that correspond to your source code statements. The
machine language instructions created by the compiler are called ob!ect code, and the
disk file containing them is called an ob!ect file.
'(T&) This book covers A+5, 5tandard C. This means that it doesn(t matter which C
compiler you use, as long as it follows the A+5, 5tandard.
<ach compiler needs its own command to be used to create the ob=ect code. To compile,
you typically use the command to run the compiler followed by the source filename. The
following are e2amples of the commands issued to compile a source file called
!A,*5.C using various B5EWindows compilers)
Com#iler Command
>icrosoft C cl radius.c
"orland(s Turbo C tcc radius.c
"orland C bcc radius.c
Iortec C 6tc radius.c
To compile !A,*5.C on a *+,- machine, use the following command)
cc radius.c
Consult the compiler manual to determine the e2act command for your compiler.
,f you(re using a graphical development environment, compiling is even simpler. ,n most
graphical environments, you can compile a program listing by selecting the compile icon
or selecting something from a menu. Bnce the code is compiled, selecting the run icon or
selecting something from a menu will e2ecute the program. You should check your
compiler(s manuals for specifics on compiling and running a program.
After you compile, you have an ob=ect file. ,f you look at a list of the files in the directory
or folder in which you compiled, you should find a file that has the same name as your
source file, but with an .B"; .rather than a .C/ e2tension. The .B"; e2tension is
recogni6ed as an ob=ect file and is used by the linker. Bn *+,- systems, the compiler
creates ob=ect files with an e2tension of .B instead of .B";.
Lin*ing to Create an &+e#uta,"e -i"e
Bne more step is re3uired before you can run your program. 4art of the C language is a
function library that contains ob!ect code .code that has already been compiled/ for
predefined functions. A #redefined function contains C code that has already been written
and is supplied in a ready1to1use form with your compiler package.
The printf./ function used in the previous e2ample is a library function. These library
functions perform fre3uently needed tasks, such as displaying information on1screen and
reading data from disk files. ,f your program uses any of these functions .and hardly a
program e2ists that doesn(t use at least one/, the ob=ect file produced when your source
code was compiled must be combined with ob=ect code from the function library to create
the final e2ecutable program. .%&ecutable means that the program can be run, or
e2ecuted, on your computer./ This process is called linkin$, and it(s performed by a
program called .you guessed it/ a linker.
0igure $.$ shows the progression from source code to ob=ect code to e2ecutable program.
-igure 1.1. The C source code that you write is conerted to ob!ect code by the com#iler
and then to an e&ecutable file by the linker'
Comp"eting the e!e"opment Cy#"e
Bnce your program is compiled and linked to create an e2ecutable file, you can run it by
entering its name at the system prompt or =ust like you would run any other program. ,f
you run the program and receive results different from what you thought you would, you
need to go back to the first step. You must identify what caused the problem and correct it
in the source code. When you make a change to the source code, you need to recompile
and relink the program to create a corrected version of the e2ecutable file. You keep
following this cycle until you get the program to e2ecute e2actly as you intended.
Bne final note on compiling and linking) Although compiling and linking are mentioned
as two separate steps, many compilers, such as the B5 compilers mentioned earlier, do
both as one step. !egardless of the method by which compiling and linking are
accomplished, understand that these two processes, even when done with one command,
are two separate actions.
The C e!e"opment Cy#"e
5tep
$
*se an editor to write your source code. "y tradition, C source code files have the
e2tension .C .for e2ample, >Y4!BJ.C, ATA"A5<.C, and so on/.
5tep
'
Compile the program using a compiler. ,f the compiler doesn(t find any errors in the
program, it produces an ob=ect file. The compiler produces ob=ect files with an .B";
e2tension and the same name as the source code file .for e2ample, >Y4!BJ.C
compiles to >Y4!BJ.B";/. ,f the compiler finds errors, it reports them. You must
return to step $ to make corrections in your source code.
5tep
8
#ink the program using a linker. ,f no errors occur, the linker produces an e2ecutable
program located in a disk file with an .<-< e2tension and the same name as the
ob=ect file .for e2ample, >Y4!BJ.B"; is linked to create >Y4!BJ.<-</.
5tep
C
<2ecute the program. You should test to determine whether it functions properly. ,f
not, start again with step $ and make modifications and additions to your source
code.
0igure $.' shows the program development steps. 0or all but the simplest programs, you
might go through this se3uence many times before finishing your program. <ven the most
e2perienced programmers can(t sit down and write a complete, error1free program in =ust
one stepA "ecause you(ll be running through the edit1compile1link1test cycle many times,
it(s important to become familiar with your tools) the editor, compiler, and linker.
-igure 1.2. The ste#s inoled in C #ro$ram deelo#ment'
.our -irst C Program
You(re probably eager to try your first program in C. To help you become familiar with
your compiler, here(s a 3uick program for you to work through. You might not understand
everything at this point, but you should get a feel for the process of writing, compiling,
and running a real C program.
This demonstration uses a program named H<##B.C, which does nothing more than
display the words Hello, WorldA on1screen. This program, a traditional introduction to C
programming, is a good one for you to learn. The source code for H<##B.C is in #isting
$.$. When you type in this listing, you won(t include the line numbers or colons.
Listing 1.1. H&LL(.C.
1: #include <stdio.h>
:
!: main()
": #
$: printf("Hello, %orld!&n");
': return (;
): *
"e sure that you have installed your compiler as specified in the installation instructions
provided with the software. Whether you are working with *+,-, B5, or any other
operating system, make sure you understand how to use the compiler and editor of your
choice. Bnce your compiler and editor are ready, follow these steps to enter, compile, and
e2ecute H<##B.C.
&ntering an% Compi"ing H&LL(.C
To enter and compile the H<##B.C program, follow these steps)
1. >ake active the directory your C programs are in and start your editor. As
mentioned previously, any te2t editor can be used, but most C compilers .such as
"orland(s Turbo C@@ and >icrosoft(s ?isual CEC@@/ come with an integrated
development environment .,</ that lets you enter, compile, and link your
programs in one convenient setting. Check the manuals to see whether your
compiler has an ,< available.
2. *se the keyboard to type the H<##B.C source code e2actly as shown in
#isting $.$. 4ress <nter at the end of each line.
'(T&) on(t enter the line numbers or colons. These are for reference only.
3. 5ave the source code. You should name the file H<##B.C.
4. ?erify that H<##B.C is on disk by listing the files in the directory or folder.
You should see H<##B.C within this listing.
/. Compile and link H<##B.C. <2ecute the appropriate command specified by
your compiler(s manuals. You should get a message stating that there were no
errors or warnings.
0. Check the compiler messages. ,f you receive no errors or warnings, everything
should be okay.
,f you made an error typing the program, the compiler will catch it and display an
error message. 0or e2ample, if you misspelled the word printf as prntf, you would
see a message similar to the following)
+rror: undefined s,m-ols:.prntf in hello.c (hello./01)
1. Jo back to step ' if this or any other error message is displayed. Bpen the
H<##B.C file in your editor. Compare your file(s contents carefully with #isting
$.$, make any necessary corrections, and continue with step 8.
2. Your first C program should now be compiled and ready to run. ,f you display a
directory listing of all files named H<##B .with any e2tension/, you should see
the following)
H<##B.C, the source code file you created with your editor
H<##B.B"; or H<##B.B, which contains the ob=ect code for H<##B.C
H<##B.<-<, the e2ecutable program created when you compiled and linked
H<##B.C
3. To e&ecute, or run, H<##B.<-<, simply enter hello. The message Hello,
WorldA is displayed on1screen.
CongratulationsA You have =ust entered, compiled, and run your first C program.
Admittedly, H<##B.C is a simple program that doesn(t do anything useful, but it(s a start.
,n fact, most of today(s e2pert C programmers started learning C in this same way11by
compiling H<##B.C11so you(re in good company.
Compi"ation &rrors
A compilation error occurs when the compiler finds something in the source code that it
can(t compile. A misspelling, typographical error, or any of a do6en other things can cause
the compiler to choke. 0ortunately, modern compilers don(t =ust chokeD they tell you what
they(re choking on and where it isA This makes it easier to find and correct errors in your
source code.
This point can be illustrated by introducing a deliberate error into H<##B.C. ,f you
worked through that e2ample .and you should have/, you now have a copy of H<##B.C
on your disk. *sing your editor, move the cursor to the end of the line containing the call
to printf./, and erase the terminating semicolon. H<##B.C should now look like #isting
$.'.
Listing 1.2. H&LL(.C 4ith an error.
1: #include <stdio.h>
:
!: main()
": #
$: printf("Hello, %orld!")
': return (;
): *
+e2t, save the file. You(re now ready to compile it. o so by entering the command for
your compiler. "ecause of the error you introduced, the compilation is not completed.
!ather, the compiler displays a message similar to the following)
hello.c(') : +rror: 2;3 e4pected
#ooking at this line, you can see that it has three parts)
hello.c The name of the file where the error was found
.H/ ) The line number where the error was found
<rror) KD( e2pected A description of the error
This message is 3uite informative, telling you that in line H of H<##B.C the compiler
e2pected to find a semicolon but didn(t. However, you know that the semicolon was
actually omitted from line F, so there is a discrepancy. You(re faced with the pu66le of
why the compiler reports an error in line H when, in fact, a semicolon was omitted from
line F. The answer lies in the fact that C doesn(t care about things like breaks between
lines. The semicolon that belongs after the printf./ statement could have been placed on
the ne2t line .although doing so would be bad programming practice/. Bnly after
encountering the ne2t command .return/ in line H is the compiler sure that the semicolon
is missing. Therefore, the compiler reports that the error is in line H.
This points out an undeniable fact about C compilers and error messages. Although the
compiler is very clever about detecting and locali6ing errors, it(s no <instein. *sing your
knowledge of the C language, you must interpret the compiler(s messages and determine
the actual location of any errors that are reported. They are often found on the line
reported by the compiler, but if not, they are almost always on the preceding line. You
might have a bit of trouble finding errors at first, but you should soon get better at it.
'(T&) The errors reported might differ depending on the compiler. ,n most cases, the
error message should give you an idea of what or where the problem is.
"efore leaving this topic, let(s look at another e2ample of a compilation error. #oad
H<##B.C into your editor again and make the following changes)
1. !eplace the semicolon at the end of line F.
2. elete the double 3uotation mark =ust before the word Hello.
5ave the file to disk and compile the program again. This time, the compiler should
display error messages similar to the following)
hello.c($) : +rror: undefined identifier 2Hello3
hello.c()) : 5e4ical error: unterminated strin6
5e4ical error: unterminated strin6
5e4ical error: unterminated strin6
7atal error: premature end of source file
The first error message finds the error correctly, locating it in line F at the word Hello.
The error message undefined identifier means that the compiler doesn(t know what to
make of the word Hello, because it is no longer enclosed in 3uotes. However, what about
the other four errors that are reported9 These errors, the meaning of which you don(t need
to worry about now, illustrate the fact that a single error in a C program can sometimes
cause multiple error messages.
The lesson to learn from all this is as follows) ,f the compiler reports multiple errors, and
you can find only one, go ahead and fi2 that error and recompile. You might find that
your single correction is all that(s needed, and the program will compile without errors.
Lin*er &rror 5essages
#inker errors are relatively rare and usually result from misspelling the name of a C
library function. ,n this case, you get an <rror) undefined symbols) error message,
followed by the misspelled name .preceded by an underscore/. Bnce you correct the
spelling, the problem should go away.
$ummary
After reading this chapter, you should feel confident that selecting C as your
programming language is a wise choice. C offers an unparalleled combination of power,
popularity, and portability. These factors, together with C(s close relationship to the C@@
ob=ect1oriented language as well as ;ava, make C unbeatable.
This chapter e2plained the various steps involved in writing a C program11the process
known as program development. You should have a clear grasp of the edit1compile1link1
test cycle, as well as the tools to use for each step.
<rrors are an unavoidable part of program development. Your C compiler detects errors
in your source code and displays an error message, giving both the nature and the
location of the error. *sing this information, you can edit your source code to correct the
error. !emember, however, that the compiler can(t always accurately report the nature and
location of an error. 5ometimes you need to use your knowledge of C to track down
e2actly what is causing a given error message.
67A
6 8f 8 4ant to gi!e someone a program 8 4rote9 4hi#h fi"es %o 8 nee% to gi!e
him?
A Bne of the nice things about C is that it is a compiled language. This means that
after the source code is compiled, you have an e2ecutable program. This
e2ecutable program is a stand1alone program. ,f you wanted to give H<##B to all
your friends with computers, you could. All you need to give them is the
e2ecutable program, H<##B.<-<. They don(t need the source file, H<##B.C, or
the ob=ect file, H<##B.B";. They don(t need to own a C compiler, either.
6 After 8 #reate an e+e#uta,"e fi"e9 %o 8 nee% to *eep the sour#e fi"e :.C; or
o,<e#t fi"e :.(B=;?
A ,f you get rid of the source file, you have no way to make changes to the
program in the future, so you should keep this file. The ob=ect files are a different
matter. There are reasons to keep ob=ect files, but they are beyond the scope of
what you(re doing now. 0or now, you can get rid of your ob=ect files once you
have your e2ecutable file. ,f you need the ob=ect file, you can recompile the
source file.
>ost integrated development environments create files in addition to the source
file ..C/, the ob=ect file ..B"; or .B/, and the e2ecutable file. As long as you keep
the source file ..C/, you can always recreate the other files.
6 8f my #ompi"er #ame 4ith an e%itor9 %o 8 ha!e to use it?
A efinitely not. You can use any editor, as long as it saves the source code in
te2t format. ,f the compiler came with an editor, you should try to use it. ,f you
like a different editor better, use it. , use an editor that , purchased separately,
even though all my compilers have their own editors. The editors that come with
compilers are getting better. 5ome of them automatically format your C code.
Bthers color1code different parts of your source file to make it easier to find
errors.
6 Can 8 ignore 4arning messages?
A 5ome warning messages don(t affect how the program runs, and some do. ,f the
compiler gives you a warning message, it(s a signal that something isn(t right.
>ost compilers let you set the warning level. "y setting the warning level, you
can get only the most serious warnings, or you can get all the warnings, including
the most minute. 5ome compilers even offer various levels in1between. ,n your
programs, you should look at each warning and make a determination. ,t(s always
best to try to write all your programs with absolutely no warnings or errors. .With
an error, your compiler won(t create the e2ecutable file./
Wor*shop
The Workshop provides 3ui6 3uestions to help you solidify your understanding of the
material covered and e2ercises to provide you with e2perience in using what you(ve
learned. Try to understand the 3ui6 and e2ercise answers before continuing to the ne2t
chapter. Answers are provided in Appendi2 J, LAnswers.L
6ui>
1. Jive three reasons why C is the best choice of programming language.
2. What does the compiler do9
3. What are the steps in the program development cycle9
4. What command do you need to enter in order to compile a program called
4!BJ!A>$.C with your compiler9
/. oes your compiler do both the linking and compiling with =ust one command,
or do you have to enter separate commands9
0. What e2tension should you use for your C source files9
1. ,s 0,#<+A><.T-T a valid name for a C source file9
2. ,f you e2ecute a program that you have compiled and it doesn(t work as you
e2pected, what should you do9
3. What is machine language9
1?. What does the linker do9
&+er#ises
1. *se your te2t editor to look at the ob=ect file created by #isting $.$. oes the
ob=ect file look like the source file9 .on(t save this file when you e2it the editor./
2. <nter the following program and compile it. What does this program do9 .on(t
include the line numbers or colons./
1: #include <stdio.h>
:
!: int radius, area;
":
$: main()
': #
): printf( "+nter radius (i.e. 1(): " );
8: scanf( "9d", :radius );
;: area < (int) (!.1"1$; = radius = radius);
1(: printf( "&n&n>rea < 9d&n", area );
11: return (;
1: *
3. <nter and compile the following program. What does this program do9
1: #include <stdio.h>
:
!: int 4,,;
":
$: main()
': #
): for ( 4 < (; 4 < 1(; 4??, printf( "&n" ) )
8: for ( , < (; , < 1(; ,?? )
;: printf( "@" );
1(:
11: return (;
1: *
4. BU@ BU$T&A) The following program has a problem. <nter it in your editor
and compile it. Which lines generate error messages9
1: #include <stdio.h>
:
!: main();
": #
$: printf( "Aeep looBin6!" );
': printf( "Cou&3ll find it!&n" );
): return (;
8: *
/. BU@ BU$T&A) The following program has a problem. <nter it in your editor
and compile it. Which lines generate problems9
1: #include <stdio.h>
:
!: main()
": #
$: printf( "Dhis is a pro6ram Eith a " );
': do.it( "pro-lem!");
): return (;
8: *
0. >ake the following change to the program in e2ercise 8. !ecompile and rerun
this program. What does the program do now9
;: printf( "9c", 1 );
<very C program consists of several components combined in a certain way. >ost of this
book is devoted to e2plaining these various program components and how you use them.
To get the overall picture, however, you should begin by seeing a complete .though
small/ C program with all its components identified. Today you will learn
About a short C program and its components
The purpose of each program component
How to compile and run a sample program
A $hort C Program
#isting '.$ presents the source code for >*#T,4#Y.C. This is a very simple program. All
it does is input two numbers from the keyboard and calculate their product. At this stage,
don(t worry about understanding the details of the program(s workings. The point is to
gain some familiarity with the parts of a C program so that you can better understand the
listings presented later in this book.
"efore looking at the sample program, you need to know what a function is, because
functions are central to C programming. A function is an independent section of program
code that performs a certain task and has been assigned a name. "y referencing a
function(s name, your program can e2ecute the code in the function. The program also
can send information, called ar$uments, to the function, and the function can return
information to the main part of the program. The two types of C functions are library
functions, which are a part of the C compiler package, and user"defined functions, which
you, the programmer, create. You will learn about both types of functions in this book.
+ote that, as with all the listings in this book, the line numbers in #isting '.$ are not part
of the program. They are included only for identification purposes, so don(t type them.
Listing 2.1. 5ULT8PL..C.
1: F= Gro6ram to calculate the product of tEo num-ers. =F
: #include <stdio.h>
!:
": int a,-,c;
$:
': int product(int 4, int ,);
):
8: main()
;: #
1(: F= Hnput the first num-er =F
11: printf("+nter a num-er -etEeen 1 and 1((: ");
1: scanf("9d", :a);
1!:
1": F= Hnput the second num-er =F
1$: printf("+nter another num-er -etEeen 1 and 1((: ");
1': scanf("9d", :-);
1):
18: F= Ialculate and displa, the product =F
1;: c < product(a, -);
(: printf ("9d times 9d < 9d&n", a, -, c);
1:
: return (;
!: *
":
$: F= 7unction returns the product of its tEo ar6uments =F
': int product(int 4, int ,)
): #
8: return (4 = ,);
;: *
+nter a num-er -etEeen 1 and 1((: 35
+nter another num-er -etEeen 1 and 1((: 23
!$ times ! < 8($
The ProgramBs Components
The following sections describe the various components of the preceding sample
program. #ine numbers are included so that you can easily identify the program parts
being discussed.
The main:; -un#tion :Lines 2 Through 23;
The only component that is re3uired in every C program is the main./ function. ,n its
simplest form, the main./ function consists of the name main followed by a pair of empty
parentheses ..// and a pair of braces .MN/. Within the braces are statements that make up
the main body of the program. *nder normal circumstances, program e2ecution starts at
the first statement in main./ and terminates at the last statement in main./.
The Cin#"u%e ire#ti!e :Line 2;
The Oinclude directive instructs the C compiler to add the contents of an include file into
your program during compilation. An include file is a separate disk file that contains
information needed by your program or the compiler. 5everal of these files .sometimes
called header files/ are supplied with your compiler. You never need to modify the
information in these filesD that(s why they(re kept separate from your source code. ,nclude
files should all have an .H e2tension .for e2ample, 5T,B.H/.
You use the Oinclude directive to instruct the compiler to add a specific include file to
your program during compilation. The Oinclude directive in this sample program means
LAdd the contents of the file 5T,B.H.L >ost C programs re3uire one or more include
files. >ore information about include files is presented on ay '$, LAdvanced Compiler
*se.L
The Daria,"e efinition :Line 4;
A ariable is a name assigned to a data storage location. Your program uses variables to
store various kinds of data during program e2ecution. ,n C, a variable must be defined
before it can be used. A variable definition informs the compiler of the variable(s name
and the type of data it is to hold. ,n the sample program, the definition on line C, int
a,b,cD, defines three variables11named a, b, and c11that will each hold an integer value.
>ore information about variables and variable definitions is presented on ay 8, L5toring
ata) ?ariables and Constants.L
The -un#tion Prototype :Line 0;
A function #rototy#e provides the C compiler with the name and arguments of the
functions contained in the program. ,t must appear before the function is used. A function
prototype is distinct from a function definition, which contains the actual statements that
make up the function. .0unction definitions are discussed in more detail later in this
chapter./
Program $tatements :Lines 119 129 1/9 109 139 2?9 229 an% 22;
The real work of a C program is done by its statements. C statements display information
on1screen, read keyboard input, perform mathematical operations, call functions, read
disk files, and carry out all the other operations that a program needs to perform. >ost of
this book is devoted to teaching you the various C statements. 0or now, remember that in
your source code, C statements are generally written one per line and always end with a
semicolon. The statements in >*#T,4#Y.C are e2plained briefly in the following
sections.
printf:;
The printf./ statement .lines $$, $F, and 'G/ is a library function that displays information
on1screen. The printf./ statement can display a simple te2t message .as in lines $$ and $F/
or a message and the value of one or more program variables .as in line 'G/.
s#anf:;
The scanf./ statement .lines $' and $H/ is another library function. ,t reads data from the
keyboard and assigns that data to one or more program variables.
The program statement on line $% calls the function named product./. ,n other words, it
e2ecutes the program statements contained in the function product./. ,t also sends the
arguments a and b to the function. After the statements in product./ are completed,
product./ returns a value to the program. This value is stored in the variable named c.
return
#ines '' and '7 contain return statements. The return statement on line '7 is part of the
function product./. ,t calculates the product of the variables 2 and y and returns the result
to the program statement that called product./. The return statement on line '' returns a
value of G to the operating system =ust before the program ends.
The -un#tion efinition :Lines 20 Through 23;
A function is an independent, self1contained section of code that is written to perform a
certain task. <very function has a name, and the code in each function is e2ecuted by
including that function(s name in a program statement. This is known as callin$ the
function.
The function named product./, in lines 'H through '%, is a user1defined function. As the
name implies, user1defined functions are written by the programmer during program
development. This function is simple. All it does is multiply two values and return the
answer to the program that called it. Bn ay F, L0unctions) The "asics,L you will learn
that the proper use of functions is an important part of good C programming practice.
+ote that in a real C program, you probably wouldn(t use a function for a task as simple
as multiplying two numbers. ,(ve done this here for demonstration purposes only.
C also includes library functions that are a part of the C compiler package. #ibrary
functions perform most of the common tasks .such as screen, keyboard, and disk
inputEoutput/ your program needs. ,n the sample program, printf./ and scanf./ are library
functions.
Program Comments :Lines 19 1?9 149 129 an% 2/;
Any part of your program that starts with EP and ends with PE is called a comment. The
compiler ignores all comments, so they have absolutely no effect on how a program
works. You can put anything you want into a comment, and it won(t modify the way your
program operates. A comment can span part of a line, an entire line, or multiple lines.
Here are three e2amples)
F= > sin6leJline comment =F
int a,-,c; F= > partialJline comment =F
F= a comment
spannin6
multiple lines =F
However, you shouldn(t use nested comments .in other words, you shouldn(t put one
comment within another/. >ost compilers would not accept the following)
F=
F= Kested comment =F
=F
5ome compilers do allow nested comments. Although this feature might be tempting to
use, you should avoid doing so. "ecause one of the benefits of C is portability, using a
feature such as nested comments might limit the portability of your code. +ested
comments also might lead to hard1to1find problems.
>any beginning programmers view program comments as unnecessary and a waste of
time. This is a mistakeA The operation of your program might be 3uite clear while you(re
writing it11particularly when you(re writing simple programs. However, as your programs
become larger and more comple2, or when you need to modify a program you wrote si2
months ago, you(ll find comments invaluable. +ow is the time to develop the habit of
using comments liberally to document all your programming structures and operations.
'(T&) >any people have started using a newer style of comments in their C programs.
Within C@@ and ;ava, you can use double forward slashes to signal a comment. Here are
two e2amples)
FF Dhis entire line is a comment
int 4; FF Iomment starts Eith slashes.
The two forward slashes signal that the rest of the line is a comment. Although many C
compilers support this form of comment, you should avoid it if you(re interested in
portability.
( add abundant comments to your program(s source code, especially near statements or
functions that could be unclear to you or to someone who might have to modify it later.
('BT add unnecessary comments to statements that are already clear. 0or e2ample,
entering
F= Dhe folloEin6 prints Hello %orld! on the screen =F
printf("Hello %orld!");
might be going a little too far, at least once you(re completely comfortable with the
printf./ function and how it works.
( learn to develop a style that will be helpful. A style that(s too lean or cryptic doesn(t
help, nor does one that(s so verbose that you(re spending more time commenting than
programmingA
Bra#es :Lines 39 239 219 an% 23;
You use braces .MN/ to enclose the program lines that make up every C function11
including the main./ function. A group of one or more statements enclosed within braces
is called a block. As you will see in later chapters, C has many uses for blocks.
Aunning the Program
Take the time to enter, compile, and run >*#T,4#Y.C. ,t provides additional practice in
using your editor and compiler. !ecall these steps from ay $, LJetting 5tarted with CL)
1. >ake your programming directory current.
2. 5tart your editor.
3. <nter the source code for >*#T,4#Y.C e2actly as shown in #isting '.$, but be
sure to omit the line numbers and colons.
4. 5ave the program file.
/. Compile and link the program by entering the appropriate command.s/ for your
compiler. ,f no error messages are displayed, you can run the program by entering
multiply at the command prompt.
0. ,f one or more error messages are displayed, return to step ' and correct the
errors.
A 'ote on A##ura#y
A computer is fast and accurate, but it also is completely literal. ,t doesn(t know enough
to correct your simplest mistakeD it takes everything you enter e2actly as you entered it,
not as you meant itA
This goes for your C source code as well. A simple typographical error in your program
can cause the C compiler to choke, gag, and collapse. 0ortunately, although the compiler
isn(t smart enough to correct your errors .and you(ll make errors11everyone doesA/, it is
smart enough to recogni6e them as errors and report them to you. .You saw in the
preceding chapter how the compiler reports error messages and how you interpret them./
A Ae!ie4 of the Parts of a Program
+ow that all the parts of a program have been described, you should be able to look at
any program and find some similarities. #ook at #isting '.' and see whether you can
identify the different parts.
Listing 2.2. L8$TE8T.C.
1: F= 5HLD.HD.IJJDhis pro6ram displa,s a listin6 Eith line num-ers! =F
: #include <stdio.h>
!: #include <stdli-.h>
":
$: Moid displa,.usa6e(Moid);
': int line;
):
8: main( int ar6c, char =ar6MNO )
;: #
1(: char -ufferN$'O;
11: 7H5+ =fp;
1:
1!: if( ar6c < )
1": #
1$: displa,.usa6e();
1': e4it(1);
1): *
18:
1;: if (( fp < fopen( ar6MN1O, "r" )) << KP55 )
(: #
1: fprintf( stderr, "+rror openin6 file, 9s!", ar6MN1O );
: e4it(1);
!: *
":
$: line < 1;
':
): Ehile( f6ets( -uffer, $', fp ) !< KP55 )
8: fprintf( stdout, "9"d:&t9s", line??, -uffer );
;:
!(: fclose(fp);
!1: return (;
!: *
!!:
!": Moid displa,.usa6e(Moid)
!$: #
!': fprintf(stderr, "&nGroper Psa6e is: " );
!): fprintf(stderr, "&n&n5HLD.HD filename.e4t&n" );
!8: *
I:&>list_it list_it.c
1: F= 5HLD.HD.I J Dhis pro6ram displa,s a listin6 Eith line num-ers! =F
: #include <stdio.h>
!: #include <stdli-.h>
":
$: Moid displa,.usa6e(Moid);
': int line;
):
8: main( int ar6c, char =ar6MNO )
;: #
1(: char -ufferN$'O;
11: 7H5+ =fp;
1:
1!: if( ar6c < )
1": #
1$: displa,.usa6e();
1': e4it(1);
1): *
18:
1;: if (( fp < fopen( ar6MN1O, "r" )) << KP55 )
(: #
1: fprintf( stderr, "+rror openin6 file, 9s!", ar6MN1O );
: e4it(1);
!: *
":
$: line < 1;
':
): Ehile( f6ets( -uffer, $', fp ) !< KP55 )
8: fprintf( stdout, "9"d:&t9s", line??, -uffer );
;:
!(: fclose(fp);
!1: return (;
!: *
!!:
!": Moid displa,.usa6e(Moid)
!$: #
!': fprintf(stderr, "&nGroper Psa6e is: " );
!): fprintf(stderr, "&n&n5HLD.HD filename.e4t&n" );
!8: *
A'AL.$8$) #,5TQ,T.C is similar to 4!,+TQ,T.C, which you entered in e2ercise & of
ay $. #isting '.' displays saved C program listings on1screen instead of printing them
on the printer.
#ooking at this listing, you can summari6e where the different parts are. The re3uired
main./ function is in lines 7 through 8'. #ines ' and 8 have Oinclude directives. #ines H,
$G, and $$ have variable definitions. A function prototype, void displayQusage.void/, is in
line F. This program has many statements .lines $8, $F, $H, $%, '$, '', 'F, '&, '7, 8G, 8$,
8H, and 8&/. A function definition for displayQusage./ fills lines 8C through 87. "races
enclose blocks throughout the program. 0inally, only line $ has a comment. ,n most
programs, you should probably include more than one comment line.
#,5TQ,T.C calls many functions. ,t calls only one user1defined function, displayQusage./.
The library functions that it uses are e2it./ in lines $H and ''D fopen./ in line $%D fprintf./
in lines '$, '7, 8H, and 8&D fgets./ in line '&D and fclose./ in line 8G. These library
functions are covered in more detail throughout this book.
$ummary
This chapter was short, but it(s important, because it introduced you to the ma=or
components of a C program. You learned that the single re3uired part of every C program
is the main./ function. You also learned that the program(s real work is done by program
statements that instruct the computer to perform your desired actions. This chapter also
introduced you to variables and variable definitions, and it showed you how to use
comments in your source code.
,n addition to the main./ function, a C program can use two types of subsidiary functions)
library functions, supplied as part of the compiler package, and user1defined functions,
created by the programmer.
67A
6 What effe#t %o #omments ha!e on a program?
A Comments are for the programmer. When the compiler converts the source
code to ob=ect code, it throws the comments and the white space away. This
means that they have no effect on the e2ecutable program. Comments do make
your source file bigger, but this is usually of little concern. To summari6e, you
should use comments and white space to make your source code as easy to
understand and main1tain as possible.
6 What is the %ifferen#e ,et4een a statement an% a ,"o#*?
A A block is a group of statements enclosed in braces .MN/. A block can be used in
most places that a statement can be used.
6 Ho4 #an 8 fin% out 4hat "i,rary fun#tions are a!ai"a,"e?
A >any compilers come with a manual dedicated specifically to documenting the
library functions. They are usually in alphabetical order. Another way to find out
what library functions are available is to buy a book that lists them. Appendi2 <,
LCommon C 0unctions,L lists many of the available functions. After you begin to
understand more of C, it would be a good idea to read these appendi2es so that
you don(t rewrite a library function. .There(s no use reinventing the wheelA/
Wor*shop
The Workshop provides 3ui6 3uestions to help you solidify your understanding of the
material covered and e2ercises to provide you with e2perience in using what you(ve
learned.
6ui>
1. What is the term for a group of one or more C statements enclosed in braces9
2. What is the one component that must be present in every C program9
3. How do you add program comments, and why are they used9
4. What is a function9
/. C offers two types of functions. What are they, and how are they different9
0. What is the Oinclude directive used for9
1. Can comments be nested9
2. Can comments be longer than one line9
3. What is another name for an include file9
1?. What is an include file9
&+er#ises
1. Write the smallest program possible.
2. Consider the following program)
1: F= +@J.I =F
: #include <stdio.h>
!:
": Moid displa,.line(Moid);
$:
': main()
): #
8: displa,.line();
;: printf("&n Deach Courself I Hn 1 Qa,s!&n");
1(: displa,.line();
11:
1: return (;
1!: *
1":
1$: F= print asterisB line =F
1': Moid displa,.line(Moid)
1): #
18: int counter;
1;:
(: for( counter < (; counter < 1; counter?? )
1: printf("=" );
: *
!: F= end of pro6ram =F
a. What line.s/ contain statements9
,. What line.s/ contain variable definitions9
#. What line.s/ contain function prototypes9
%. What line.s/ contain function definitions9
e. What line.s/ contain comments9
3. Write an e2ample of a comment.
4. What does the following program do9 .<nter, compile, and run it./
1: F= +@J".I =F
: #include <stdio.h>
!:
": main()
$: #
': int ctr;
):
8: for( ctr < '$; ctr < ;1; ctr?? )
;: printf("9c", ctr );
1(:
11: return (;
1: *
1!: F= end of pro6ram =F
/. What does the following program do9 .<nter, compile, and run it./
1: F= +@J$.I =F
: #include <stdio.h>
!: #include <strin6.h>
": main()
$: #
': char -ufferN$'O;
):
8: printf( "+nter ,our name and press <+nter>:&n");
;: 6ets( -uffer );
1(:
11: printf( "&nCour name has 9d characters and spaces!",
1 strlen( -uffer ));
1!:
1": return (;
1$: *

Potrebbero piacerti anche