pro-You will profit from reading the book when you start to apply C programs to real lems or move on to learn other programming languages, such as Perl, C++, and Java.. Here is a summary
Trang 2201 West 103rd St., Indianapolis, Indiana, 46290 USA
Trang 3Sams Teach Yourself C in 24 Hours, Second Edition
Copyright ©2000 by Sams Publishing
All rights reserved No part of this book shall be reproduced, stored in a retrieval system, or transmitted by any means, electronic, mechanical, photo- copying, recording, or otherwise, without written permission from the pub- lisher No patent liability is assumed with respect to the use of the information contained herein Although every precaution has been taken in the preparation
of this book, the publisher and author assume no responsibility for errors or omissions Nor is any liability assumed for damages resulting from the use of the information contained herein.
International Standard Book Number: 0-672-31861-x Library of Congress Catalog Card Number: 99-067311
Printed in the United States of America
First Printing: February, 2000
05 04 03 6 5 4 3
Trademarks
All terms mentioned in this book that are known to be trademarks or service marks have been appropriately capitalized Sams Publishing cannot attest to the accuracy of this information Use of a term in this book should not be regarded
as affecting the validity of any trademark or service mark.
Warning and Disclaimer
Every effort has been made to make this book as complete and as accurate as possible, but no warranty or fitness is implied The information provided is on
an “as is” basis The author and the publisher shall have neither liability nor responsibility to any person or entity with respect to any loss or damages aris- ing from the information contained in this book.
Trang 4Contents at a Glance
Part II Operators and Control-flow Statements 89
9 Working with Data Modifiers and Math Functions 141
Part III Pointers and Arrays 173
Part IV Functions and Dynamic Memory Allocation 241
Trang 5Part V Structure, Union, File I/O, and More 311
Trang 6Table of Contents
Who Should Read This Book? 1
Special Features of This Book 1
Programming Examples 2
Q&A and Workshop 4
Conventions Used in This Book 4
What You’ll Learn in 24 Hours 4
Part I The Basics of C 9 Hour 1 Taking the First Step 11 What Is C? 12
The ANSI C Standard .15
Assumptions About You 16
Setting Up Your System 16
Hardware 16
Software 16
A Sample C Programming Setup 17
Using Microsoft’s Compiler 18
Using Borland’s Compiler 21
Summary 24
Q&A 25
Workshop 25
Quiz 25
Hour 2 Writing Your First C Program 27 A Simple C Program 28
Comments 29
The #include Directive 31
Header Files 32
Angle Brackets ( < > ) and Double Quotes ( “ “ ) 32
The main() Function 33
The Newline Character ( \n ) 33
The return Statement 34
The exit() Function 34
Compiling and Linking 34
What’s Wrong with My Program? 36
Debugging Your Program 37
Trang 7Summary 37
Q&A 38
Workshop 38
Quiz 38
Exercises 39
Hour 3 Learning the Structure of a C Program 41 The Basics of a C Program 42
Constants and Variables 42
Expressions 42
Statements 45
Statement Blocks 45
Anatomy of a C Function 46
Determining a Function’s Type 46
Giving a Function a Valid Name 47
Passing Arguments to C Functions 47
The Beginning and End of a Function 48
The Function Body 48
Making Function Calls 49
Summary 51
Q&A 52
Workshop 52
Quiz 52
Exercises 53
Hour 4 Understanding Data Types and Keywords 55 C Keywords 56
The char Data Type 57
Character Variables 58
Character Constants 58
The Escape Character (\) 59
Printing Characters 60
The int Data Type 62
Declaring Integer Variables 62
Showing the Numeric Values of Characters 63
The float Data Type 64
Declaring Floating-Point Variables 64
The Floating-Point Format Specifier ( %f ) 65
The double Data Type 67
Using Scientific Notation 67
Naming a Variable 68
Summary 68
Q&A 68
Trang 8Workshop 69
Quiz 69
Exercises 70
Hour 5 Handling Standard Input and Output 71 Understanding Standard I/O .72
Getting Input from the User 72
Using the getc() Function 72
Using the getchar() Function 74
Printing Output on the Screen 75
Using the putc() Function 75
Another Function for Writing: putchar() 77
Revisiting the printf() Function 78
Converting to Hex Numbers 79
Specifying the Minimum Field Width 81
Aligning Output 83
Using the Precision Specifier 84
Summary 85
Q&A 86
Workshop 86
Quiz 87
Exercises 87
Part II Operators and Control-flow Statements 89 Hour 6 Manipulating Data 91 Arithmetic Assignment Operators 92
The Assignment Operator ( = ) 92
Combining Arithmetic Operators with = 92
Getting Negations of Numeric Values 95
Incrementing or Decrementing by One 96
Greater Than or Less Than? 98
Using the Cast Operator 101
Summary 102
Q&A 102
Workshop 103
Quiz 103
Exercises 103
Hour 7 Working with Loops 105 The while Loop 106
The do-while Loop 107
Looping Under the Statement 109
Contents vii
Trang 9The Null Statement 112
Using Complex Expressions in a for Statement 113
Using Nested Loops 116
Summary 118
Q&A 118
Workshop 119
Quiz 119
Exercises 120
Hour 8 Using Conditional Operators 121 Measuring Data Sizes 122
Everything Is Logical 124
The Logical AND Operator ( && ) 124
The Logical OR Operator ( || ) 126
The Logical NEGATION Operator ( ! ) 128
Manipulating Bits 129
Converting Decimal to Hex or Binary 129
Using Bitwise Operators 130
Using Shift Operators 133
What Does x?y:z Mean? 135
Summary 137
Q&A 137
Workshop 138
Quiz 138
Exercises 138
Hour 9 Working with Data Modifiers and Math Functions 141 Enabling or Disabling the Sign Bit 142
The signed Modifier 142
The unsigned Modifier 143
Changing Data Sizes 145
The short Modifier 145
The long Modifier 145
Adding h , l , or L to printf and fprintf Format Specifiers 147
Mathematical Functions in C 148
Calling sin() , cos() , and tan() 149
Calling pow() and sqrt() 150
Summary 152
Q&A 153
Workshop 154
Quiz 154
Exercises 154
Trang 10Hour 10 Controlling Program Flow 155
Always Saying “ if… ” 156
The if-else Statement 158
Nested if Statements 160
The switch Statement 161
The break Statement 164
Breaking an Infinite Loop 166
The continue Statement 167
The goto Statement 168
Summary 170
Q&A 170
Workshop 171
Quiz 171
Exercises 172
Part III Pointers and Arrays 173 Hour 11 Understanding Pointers 175 What Is a Pointer? 176
Address (Left Value) Versus Content (Right Value) 176
The Address-of Operator ( & ) 177
Declaring Pointers 179
The Dereference Operator ( * ) 182
Null Pointers 183
Updating Variables via Pointers 183
Pointing to the Same Memory Location 184
Summary 186
Q&A 187
Workshop 188
Quiz 188
Exercises 188
Hour 12 Understanding Arrays 189 What Is an Array? 190
Declaring Arrays 190
Indexing Arrays 190
Initializing Arrays 191
The Size of an Array 192
Arrays and Pointers 194
Displaying Arrays of Characters 196
The Null Character ( ‘\0’ ) 198
Multidimensional Arrays 199
Trang 11Unsized Arrays 201
Summary 203
Q&A 203
Workshop 204
Quiz 204
Exercises 205
Hour 13 Manipulating Strings 207 Declaring Strings 208
What Is a String? 208
Initializing Strings 208
String Constants versus Character Constants 209
How Long Is a String? 212
The strlen() Function 212
Copying Strings with strcpy() 213
Reading and Writing Strings 215
The gets() and puts() Functions 215
Using %s with the printf() Function 217
The scanf() Function 217
Summary 219
Q&A 220
Workshop 221
Quiz 221
Exercises 221
Hour 14 Understanding Scope and Storage Classes 223 Hiding Data 224
Block Scope 224
Nested Block Scope 225
Function Scope 226
Program Scope 227
The Storage Class Specifiers 229
The auto Specifier 229
The static Specifier 230
File Scope and the Hierarchy of Scopes 232
The register Specifier 233
The extern Specifier 233
The Storage Class Modifiers 234
The const Modifier 234
The volatile Modifier 235
Summary 236
Q&A 237
Trang 12Contents xi
Workshop 238
Quiz 238
Exercises 239
Part IV Functions and Dynamic Memory Allocation 241 Hour 15 Working with Functions 243 Declaring Functions 244
Declaration Versus Definition 244
Specifying Return Types 244
Using Prototypes 245
Making Function Calls 245
Prototyping Functions 247
Functions with No Arguments 248
Using time() , localtime() , and asctime() 249
Functions with a Fixed Number of Arguments 251
Prototyping a Variable Number of Arguments 251
Processing Variable Arguments 252
Learning Structured Programming 255
Summary 255
Q&A 256
Workshop 257
Quiz 257
Exercises 257
Hour 16 Applying Pointers 259 Pointer Arithmetic 259
The Scalar Size of Pointers 260
Pointer Subtraction 263
Pointers and Arrays 264
Accessing Arrays via Pointers 264
Pointers and Functions 266
Passing Arrays to Functions 266
Passing Pointers to Functions 268
Passing Multidimensional Arrays as Arguments 270
Arrays of Pointers 272
Pointing to Functions 274
Summary 276
Q&A 276
Workshop 277
Quiz 277
Exercises 278
Trang 13Hour 17 Allocating Memory 279
Allocating Memory at Runtime 280
The malloc() Function 280
Releasing Allocated Memory with free() 283
The calloc() Function 286
The realloc() Function 288
Summary 291
Q&A 292
Workshop 293
Quiz 293
Exercises 294
Hour 18 Using Special Data Types and Functions 295 The enum Data Type 296
Declaring the enum Data Type 296
Assigning Values to enum Names 296
Making typedef Definitions 300
Why Use typedef ? 300
Recursive Functions 303
Revisiting the main() Function 305
Command-Line Arguments 305
Receiving Command-Line Arguments 306
Summary 308
Q&A 308
Workshop 309
Quiz 309
Exercises 310
Part V Structure, Union, File I/O, and More 311 Hour 19 Understanding Structures 313 What Is a Structure? 314
Declaring Structures 314
Defining Structure Variables 315
Referencing Structure Members with the Dot Operator 315
Initializing Structures 317
Structures and Function Calls 319
Referencing Structures with Pointers 322
Referencing a Structure Member with -> 324
Arrays of Structures 324
Nested Structures 327
Summary 330
Trang 14Q&A 330
Workshop 331
Quiz 331
Exercises 332
Hour 20 Understanding Unions 333 What Is a Union? 334
Declaring Unions 334
Defining Union Variables 334
Referencing a Union with or -> 335
Unions versus Structures 337
Initializing a Union 337
The Size of a Union 339
Using Unions 341
Referencing the Same Memory Location Differently 341
Making Structures Flexible 343
Defining Bit Fields with struct 347
Summary 350
Q&A 351
Workshop 352
Quiz 352
Exercises 353
Hour 21 Reading and Writing with Files 355 Files Versus Streams 356
What Is a File? 356
What Is a Stream? 356
Buffered I/O 356
The Basics of Disk File I/O 357
Pointers of FILE 357
Opening a File 357
Closing a File 358
Reading and Writing Disk Files 360
One Character at a Time 360
One Line at a Time 363
One Block at a Time 366
Summary 370
Q&A 370
Workshop 371
Quiz 371
Exercises 372
Contents xiii
Trang 15Hour 22 Using Special File Functions 373
Random Access to Disk Files 374
The fseek() and ftell() Functions 374
The rewind() Function 378
More Examples of Disk File I/O 378
Reading and Writing Binary Data 378
The fscanf() and fprintf() Functions 381
Redirecting the Standard Streams with freopen() 384
Summary 387
Q&A 387
Workshop 388
Quiz 388
Exercises 389
Hour 23 Compiling Programs: The C Preprocessor 391 What Is the C Preprocessor? 392
The C Preprocessor versus the Compiler 392
The #define and #undef Directives 393
Defining Function-Like Macros with #define 394
Nested Macro Definitions 396
Compiling Your Code Under Conditions 397
The #ifdef and #endif Directives 397
The #ifndef Directive 397
The #if , #elif , and #else Directives 399
Nested Conditional Compilation 402
Summary 405
Q&A 405
Workshop 406
Quiz 406
Exercises 407
Hour 24 Where Do You Go from Here? 409 Creating a Linked List 410
Programming Style 418
Modular Programming 419
Debugging 420
What You Have Learned 420
C Keywords 420
Operators 421
Constants 422
Data Types 423
Expressions and Statements 426
Control Flow Statements 426
Trang 16Pointers 430
Functions 432
Input and Output (I/O) 433
The C Preprocessor 434
The Road Ahead… 434
Summary 435
Part VI Appendixes 437 Appendix A ANSI Standard Header Files 439 Appendix B Answers to Quiz Questions and Exercises 441 Hour 1, “Taking the First Step” 441
Quiz 441
Hour 2, “Writing Your First C Program” 442
Quiz 442
Exercises 442
Hour 3, “Learning the Structure of a C Program” 443
Quiz 443
Exercises 444
Hour 4, “Understanding Data Types and Keywords” 445
Quiz 445
Exercises 445
Hour 5, “Handling Standard Input and Output” 447
Quiz 447
Exercises 447
Hour 6, “Manipulating Data” 449
Quiz 449
Exercises 449
Hour 7, “Working with Loops” 451
Quiz 451
Exercises 451
Hour 8, “Using Conditional Operators” 453
Quiz 453
Exercises 453
Hour 9, “Working with Data Modifiers and Math Functions” 455
Quiz 455
Exercises 456
Hour 10, “Controlling Program Flow” 458
Quiz 458
Exercises 458
Trang 17Hour 11, “Understanding Pointers” 460
Quiz 460
Exercises 461
Hour 12, “Understanding Arrays” 462
Quiz 462
Exercises 463
Hour 13, “Manipulating Strings” 465
Quiz 465
Exercises 466
Hour 14, “Understanding Scope and Storage Classes” 467
Quiz 467
Exercises 468
Hour 15, “Working with Functions” 470
Quiz 470
Exercises 470
Hour 16, “Applying Pointers” 473
Quiz 473
Exercises 474
Hour 17, “Allocating Memory” 476
Quiz 476
Exercises 476
Hour 18, “Using Special Data Types and Functions” 480
Quiz 480
Exercises 480
Hour 19, “Understanding Structures” 482
Quiz 482
Exercises 482
Hour 20, “Understanding Unions” 486
Quiz 486
Exercises 486
Hour 21, “Reading and Writing with Files” 490
Quiz 490
Exercises 490
Hour 22, “Using Special File Functions” 494
Quiz 494
Exercises 494
Hour 23, “Compiling Programs: The C Preprocessor” 499
Quiz 499
Exercises 500
Trang 18About the Author
T ONY Z HANGhas more than 15 years experience in computer programming and prise-wide information system design He is currently working for one of the “big 5”consulting firms focusing on e-business related infrastructure design, development, andimplementation
enter-With a Masters degree in Physics, he has published dozens of research papers on lasersand computer programming Among his broad interests are oil painting and photography,the two things that Tony enjoys most
You can reach Tony through Sams Publishing, or by emailing him at
tyc24h@hotmail.com
About the Contributing Author
J OHN S OUTHMAYDis a Software Design Engineer with experience in areas ranging fromsystems-level programming and device drivers to Windows development and Internettechnologies He currently works as a consultant with Excell Data Corporation and liveswith his wife in Kirkland, Washington
Trang 19It’s my great pleasure to work with editor Sharon Cox for the second time I’d like tothank editors Carol Ackerman and Gus Miklos, and contributing author John Southmaydfor their excellent work that made the second edition of the book more accessible, andlargely, if not completely, error-free Also, I’d like to express my appreciation to the greatwork of the other editing team members Together, they made the second edition possible.
I greatly appreciate the love and support of my wife, Ellen, who inspires me to look atthe technology world from different perspectives It’s always a great joy to discuss issues
on philosophy and literature with her My parents, whom I can never thank enough, gave
me not only love and affection, but also the opportunity of receiving the best education Icould ever have when I was in China
Trang 20Tell Us What You Think!
As the reader of this book, you are our most important critic and commentator We value
your opinion and want to know what we’re doing right, what we could do better, whatareas you’d like to see us publish in, and any other words of wisdom you’re willing topass our way
As an Associate Publisher for Sams, I welcome your comments You can fax, email, orwrite me directly to let me know what you did or didn’t like about this book—as well aswhat we can do to make our books stronger
Please note that I cannot help you with technical problems related to the topic of this book, and that due to the high volume of mail I receive, I might not be able to reply to every message.
When you write, please be sure to include this book’s title and author as well as yourname and phone or fax number I will carefully review your comments and share themwith the author and editors who worked on the book
Fax: 317-581-4770Email: michael.stephens@macmillanusa.com
Mail: Michael Stephens
Associate PublisherSams Publishing
201 West 103rd StreetIndianapolis, IN 46290 USA
Trang 22If one learns from others but does not think, one will be bewildered;
If one thinks but does not learn from others, one will be in peril
—Confucius
Welcome to the second edition of Teach Yourself C in 24 Hours!
Based on the success of the first edition of the book and the feedback from the readers,
we have re-written or modified every single chapter of the book to make the second tion more suitable for beginners like you who want to get started with the C program-ming language as quickly as possible
edi-Of course, it’s very normal to spend more than 24 hours to really understand the cepts and programming skills introduced in the book However, the good news is thatthis book offers many sample programs and exercises with clear explanations andanswers, which makes the concepts of the C language easier to understand
con-In fact, Teach Yourself C in 24 Hours provides a good starting point for you in C
pro-gramming It covers important topics in C programming, and lays a solid foundation for
a serious beginner like you After reading this book, you’ll be able to write basic C grams on your own
pro-You will profit from reading the book when you start to apply C programs to real lems or move on to learn other programming languages, such as Perl, C++, and Java
prob-Who Should Read This Book?
If this is your first time learning C, this book is written for you In fact, in writing thisbook I assume that the readers have no previous programming experience Of course, it’salways a big plus if you have some knowledge of computers
Special Features of This Book
This book contains the following special elements that make it simpler and clearer foryou to digest the rudimentary features and concepts of C as they are introduced:
• Syntax boxes
• Notes
• Cautions
• Tips
Trang 23Syntax boxes explain some of the more complicated features of C, such as control
struc-tures Each syntax box consists of a formal definition of the feature followed by anexplanation Here is an example of a syntax box:
The syntax for the malloc()function is
#include <stdlib.h>
void *malloc(size_t size);
Here,sizespecifies the number of bytes of storage to allocate The header file,
stdlib.h, has to be included before the malloc()function can be called Because the
malloc()function returns a voidpointer, its type is automatically converted to the type
of pointer on the left side of an assignment operator
(You’ll learn more about the malloc()function later in the book.)
Notes are explanations of interesting properties of a particular C program feature Let’s
have a look at the following example of a note:
at the right end of the value field.
Warnings warn you of programming pitfalls you should avoid Here is a typical warning:
Never use the reserved keywords in C, nor names of the C library functions
as variable names in your program.
Tips are hints on how to write your C programs better The following is an example of
Trang 24expla-Each example has a listing of the C program; the output generated from that listing willfollow The example also offers an analysis of how the program works Special icons areused to point out each part of the example: Type, Input/Output, and Analysis.
In the example shown in Listing IN.1, there are some special typographic conventions
The input you enter is shown in bold monospace type, and the output generated by theexecutable program of Listing IN.1 is shown in plain monospace type
L ISTING IN.1 Read in a Character Entered by the User
1: /* INL01.c: Read input by calling getc() */
2: #include <stdio.h>
3:
4: main() 5: { 6: int ch;
Please type in one character:
H The character you just entered is: H
In line 2 of Listing IN.1, the header file stdio.his included for both the getc()
and printf()functions used in the program Lines 4–12 give the name and body
of the main()function
In line 6, an integer variable chis declared, which is assigned to the return value fromthe getc()function later in line 9 Line 8 prints out a piece of message that asks the user
to enter one character from the keyboard The printf()function in line 8 uses thedefault standard output stdoutto display messages on the screen
In line 9, the standard input stdinis passed to the getc()function, which indicates thatthe file stream is from the keyboard After the user types in a character, the getc()func-tion returns the numeric value (that is, an integer) of the character Note that in line 9 thenumeric value is assigned to the integer variable ch
Introduction 3
TYPE
Trang 25In line 10, the character entered is displayed on the screen with the help of printf().Note that the character format specifier %cis used within the printf()function in line 10.
Q&A and Workshop
Each hour (that is, each chapter) ends with a Q&A section that contains answers to mon questions relating to the lesson of the chapter Following the Q&A section there is aWorkshop that consists of quiz questions and programming exercises The answers tothese quiz questions and sample solutions for the exercises are presented in Appendix D,
com-“Answers to Quiz and Exercises.”
To help you solidify your understanding of each lesson, you are encouraged to try toanswer the quiz questions and finish the exercises provided in the workshop
Conventions Used in This Book
This book uses special typefaces to help you differentiate between C code and regularEnglish, and to identify important concepts
• Actual C code is typeset in a special monospacefont You’ll see this font used inlistings, Input/Ouput examples, and code snippets In the explanation of C features,commands, filenames, statements, variables, and any text you see on the screen arealso typeset in this font
• Command input and anything that you are supposed to enter appears in a bold monospacefont You’ll see this mainly in the Input/Output sections of examples
• Placeholders in syntax descriptions appear in an italic monospacefont Replacethe placeholder with the actual filename, parameter, or whatever element it repre-sents
• Italics highlight technical terms when they appear for the first time in the text and
are sometimes used to emphasize important points
What You’ll Learn in 24 Hours
Teach Yourself C in 24 Hours consists of five parts In Part I, “The Basics of C,” you’ll
learn the basics of the C language Here is a summary of what you’re going to learn:
Hour 1, “Taking the First Step,” introduces you to the C language, the ANSI
stan-dard, and the basic software and hardware requirements for C programming
Hour 2, “Your First C Program,” demonstrates the entire procedure of writing,
compiling, linking, and running a C program
Trang 26Hour 3, “Learning the Structure of a C Program,” teaches you several important
concepts, such as constants, variables, expressions, and statements The anatomy of afunction is introduced in this hour as well
Hour 4, “Understanding Data Types and Keywords,” lists all reserved C keywords.
Four data types,char,int,float, and double, are introduced in detail Also, the rulesfor naming a variable are explained
Hour 5, “Handling Standard Input and Output,” teaches you to receive input from
the keyboard, and print output on the screen with the help of a set of C functions,such as getc(),getchar(),putc(),putchar(), and printf()
Part II, “Operators and Control-flow Statements,” emphasizes operators and control-flowstatements in C The following is a summary of what you’ll learn:
Hour 6, “Manipulating Data,” teaches you how to use arithmetic assignment
opera-tors, the unary minus operator, increment/decrement operaopera-tors, relational operaopera-tors,and the cast operator
Hour 7, “Working with Loops,” introduces looping (that is, iteration) with the for,
while, or do-whilestatements
Hour 8, “Using Conditional Operators,” tells you about more operators, such as
logical operators, bitwise operators, the sizeofoperator, and ?:operator, which arefrequently used in C
Hour 9, “Working with Data Modifiers and Math Functions,” describes how to
use data modifiers to enable or disable the sign bit, or change the size of a data type
Also, several mathematical functions provided by C are introduced
Hour 10, “Controlling Program Flow,” introduces all the control-flow statements
used in C They are the if,if-else,switch,break,continue, and gotostatements
Pointers and arrays are discussed in Part III, “Pointers and Arrays.” The following is asummary of what you’ll learn:
Hour 11, “Understanding Pointers,” teaches you how to reference variables with
pointers Concepts such as left value and right value are also introduced
Hour 12, “Understanding Arrays,” explains how to declare and initialize arrays.
The relationship between the array and the pointer in C is discussed too
Hour 13, “Manipulating Strings” focuses on reading and writing strings Several C
library functions, such as strlen(),strcpy(),gets(),puts(), and scanf(), areintroduced to manipulate strings
Hour 14, “Understanding Scope and Storage Classes,” introduces block scope,
func-tion scope, program scope, and file scope In addifunc-tion, storage class specifiers or fiers, such as auto,static,register,extern,const, and volatileare explained
modi-Introduction 5
Trang 27Part IV, “Functions and Dynamic Memory Allocation,” focuses on functions anddynamic memory allocations in C The following is a summary of what you’ll learn:
Hour 15, “Working with Functions,” describes the function declaration and
defini-tion in C The funcdefini-tion prototyping is explained, along with the funcdefini-tion return typespecification
Hour 16, “Applying Pointers” teaches you how to perform pointer arithmetic
opera-tions, access elements in arrays with pointers, and how to pass pointers to functions
Hour 17, “Allocating Memory” explains the concept of allocating memory
dynami-cally C functions, such as malloc(),calloc(),realloc(), and free(), are duced with regard to the dynamic memory allocation
intro-Hour 18, “Using Special Data Types and Functions,” introduces the enumdata typeand the use of typedef Function recursion and command-line arguments to the
main()function are also taught in Hour 18
Part V, “Structure, Union, File I/O, and More,” discusses structures, unions, and disk fileI/O in C The following is a summary of what you’ll learn:
Hour 19, “Understanding Structures,” introduces the structuredata type Youlearn to access structure members, and pass structures to functions with the help ofpointers Nested and forward-referencing structures are also discussed in this hour
Hour 20, “Understanding Unions,” describes the uniondata type, and the differencebetween unionand structure The applications of unions are demonstrated in severalexamples
Hour 21, “Reading and Writing with Files,” explains the concepts of the file and
the stream in C The basics of disk file input and output are introduced in this firstpart The following C functions, along with several examples are, introduced in thishour:fopen(),fclose(),fgetc(),fputc(),fgets(),fputs(),fread(),fwrite(),and feof()
Hour 22, “Using Special File Functions,” is the second part of disk file I/O, in
which fseek(),ftell(), and rewind()are introduced to show how they can helpyou to get random access to disk files In addition, the fscanf(),fprintf(), and
freopen()functions are taught and invoked in sample programs
Hour 23, “Compiling Programs: The C Preprocessor,” describes the role played by
the C preprocessor You can learn the preprocessor directives, such as #define,
#undef,#ifdef,#endif,#ifndef,#if,#elis, and #elsethrough the examples given
in this hour
Trang 28Hour 24, “Where Do You Go from Here?,” summarizes the important concepts and
features introduced in this book In addition, programming style, modular ming, and debugging are explained briefly A list of recommended C books is pro-vided for your further reading
program-Now, you’re ready to start the journey of learning the C language, as the world has movedinto a new millennium Have a fun in reading this book, and enjoy programming in C!
Tony ZhangDowningtown, PennsylvaniaJanuary, 2000
Introduction 7
Trang 301 Taking the First Step
2 Your First C Program
3 Learning the Structure of a C program
4 Understanding Data Types and Keywords
5 Handling Standard Input and Output
The Basics of C
Trang 32H OUR 1
Taking the First Step
A journey of a thousand miles is started by taking the first step.
• Why you need to learn C
• The ANSI standard
• Hardware and software required to write and run C programs
Trang 33What Is C?
C is a programming language The C language was first developed in 1972 by Dennis
Ritchie at AT&T Bell Labs Ritchie called his newly developed language C simply because there was a B programming language already (As a matter of fact, the B lan-
guage led to the development of C.)
C is a high-level programming language In fact, C is one of the most popular purpose programming languages
general-In the computer world, the further a programming language is from the computer tecture, the higher the language’s level You can imagine that the lowest-level languagesare machine languages that computers understand and execute directly The high-levelprogramming languages, on the other hand, are closer to our human languages (seeFigure 1.1)
archi-F IGURE 1.1
The language
to the Internet;
else, wait
If (line ! = busy) connect (Internet);
else wait (5)
10001111101100 01100111011000 Low
High
High-level programming languages, including C, have the following advantages:
• Readability: Programs are easy to read.
• Maintainability: Programs are easy to maintain.
• Portability: Programs are easy to port across different computer platforms.
Trang 34The C language’s readability and maintainability benefit directly from its relative ness to human languages, especially English.
close-Each high-level language needs a compiler or an interpreter to translate instructions
written in the high-level programming language into a machine language that a puter can understand and execute Different machines may need different compilers orinterpreters for the same programming language For instance, I use Microsoft’s C com-piler to compile the C programs in this book for my personal computer (PC) If I need torun the C programs on a UNIX-based workstation, I have to use another type of C com-piler to compile these programs Therefore, the portability of programs written in C isrealized by re-compiling the programs with different compilers for different machines(see Figure 1.2)
com-Taking the First Step 13
1
F IGURE 1.2
Porting programs
writ-ten in C into different
types of computers.
The C Program
Compiler A
Compiler B
Compiler C
The Computer’s Brain
You may know that the brain of a computer is the central processing unit (CPU) Some computers may have more than one CPU inside A CPU has millions of transistors that make use of electronic switches The electronic switches have only two states: off and on.
(Symbolically, 0 and 1 are used to represent the two states.) Therefore, a computer can only understand instructions consisting of series of 0 s and 1 s In other words, machine- readable instructions have to be in binary format.
Trang 35In addition, the C language has other advantages Programs written in C can be reused.You can save parts of your C programs into a library file and invoke them in your nextprogramming project simply by including the library file Many common and useful pro-gramming tasks are already implemented in libraries that come included with compilers.
In addition, libraries allow you to easily unleash the power and functionality of the ating system you are using More details on using C library functions are covered in therest of this book
oper-C is a relatively small programming language, which makes life easier for you You don’thave to remember many C keywords or commands before you start to write programs in
C to solve problems in the real world
For those who seek speed while still keeping the convenience and elegance of a level language, the C language is probably the best choice In fact, C allows you to getcontrol of computer hardware and peripherals That’s why the C language is sometimescalled the lowest high-level programming language
high-Many other high-level languages have been developed based on C For instance, Perl is apopular programming language in World Wide Web (WWW) design across the Internet.Perl actually borrows a lot of features from C If you understand C, learning Perl is asnap Another example is the C++ language, which is simply an expanded version of C,although C++ makes object-oriented programming easier Also, learning Java becomesmuch easier if you already know C
However, a computer program written in a high-level language, such as C, Java, or Perl, is just a text file, consisting of English-like characters and words You have to use special programs, called compilers or interpreters, to translate such a program into a machine- readable code That is, the text format of all instructions written in a high-level language has to be converted into binary format The code obtained after the translation is called
binary code Prior to the translation, a program in text format is called source code The smallest unit of binary code is called a bit (from binary digit), which can have a value
of 0 or 1 Generally, eight bits make up one byte, and half a byte (four bits) is one nibble.
There are generally two types of programming languages: compiled guages and interpreted languages.
lan-A compiler is needed to translate a program written in a compiled language into machine-understandable code (that is, binary code) before you can run the program on your machine When the translation is done, the binary
Trang 36The ANSI C Standard
For many years, the de facto standard for the C programming language was the book The
C Programming Language, written by Brian Kernighan and Dennis Ritchie in 1978 This
book is commonly known in the programming community as simply K&R (referring tothe initials of the authors) and finds a place on many programmers’ bookshelves to thisday However, the book was written as a tutorial introduction to C, not as a comprehen-sive or official standard for the language As different vendors offered varying implemen-tations of the C language, differences between those implementations began to appear
Fearing that C might lose its portability, a group of compiler vendors and software opers petitioned the American National Standards Institute (ANSI) to build a standard forthe C language in 1983 ANSI approved the application and formed the X3J11 TechnicalCommittee to work on the C standard By the end of 1989, the committee approved theANSI standard for the C programming language
devel-The ANSI standard for C enhances the original K&R standard and defines a group ofcommonly used C functions that known as the ANSI C standard library In most cases, Ccompilers include the standard library, along with other libraries to provide some othercompiler-specific functions
Taking the First Step 15
1
code can be saved into an application file You can keep running the cation file without the compiler unless the program (source code) is updated and you have to recompile it The binary code or application file is also called executable code (or an executable file).
appli-On the other hand, a program written in an interpreted language can be run immediately after you finish writing it — or for that matter, while you are writing it! But such a program always needs an interpreter to translate the high-level instructions into machine-understandable instructions (binary code) at runtime You cannot run the program on a machine unless the right interpreter is available.
You can think of the C language as a compiled language because most C language vendors make only C compilers, as opposed to interpreters, to sup- port programs written in C.
However, there is nothing inherent to a compiled language to prevent someone from providing an interpreter for the language; likewise, people can and often do write compilers for interpreted languages In fact, it is not uncommon to mix the two flavors of languages, where a programmer com- piles source code into a small binary file which is then executed by a runtime interpreter.
Trang 37This book focuses on the C functions defined in the ANSI standard, which is supported
by all compiler vendors All programs in this book can be compiled by any compilersthat comply with the ANSI standard If you’re interested in a specific compiler, you canlearn the compiler-specific functions from the compiler’s reference manual
Assumptions About You
No previous programming experience is required for you to learn the C language from thisbook, although some knowledge of computers helps Also, it’s up to you to determine howquickly to go through the 24 hours of this book: You could sit up with a big pot of coffeeand power through the book in a sitting or you could take an hour a day for 24 days.After you complete this book, having done all of the exercises along the way, you should
be proficient and comfortable with the syntax and features of the C language In addition,you’ll already have some experience with many of the tasks that are encountered in Cprogramming When you’re ready to undertake your own programming projects, you’ll
be able to use C as a tool in writing the powerful and useful programs you want to ate As you progress, you’ll find that there is always more to learn—not only about Cand how to leverage its power, but also about new technologies and programming ideas
cre-in general With hard work and lots of practice, you can quickly build on the skills andtechnologies that you learn
Setting Up Your System
Basically, all you need is a computer and a C compiler in order to compile and run yourown C programs or the C programs from this book The recommended hardware andsoftware are listed in the following sections
Hardware
Any type of computer that has or can access a C compiler is fine The C compiler should
be ANSI C compliant Most likely, you have a PC on your desktop A 286 PC with a50MB hard drive and 1MB memory (RAM) is probably the minimum requirement to run
a DOS-based C compiler For a Windows-based C compiler, your computer must have abigger hard drive and more memory Check your compiler vendor for more details onhardware requirements
Software
If you’re using a UNIX-based workstation, you might already have a C compiler loaded
on your machine, or at least you might be able to access a C compiler on a servermachine Check with your system administrator to find out how to access an ANSI C
Trang 38compliant compiler On a UNIX-based machine, you should know how to use a text tor such as vior emacsto write C programs.
edi-If you have a PC running a Microsoft Windows operating system (such as Windows 95),you need to install a C compiler and a text editor on your PC However, most C compil-ers come with a built-in editor You can also use any text editor that may already beinstalled on your machine
Borland International’s Turbo C and Microsoft’s Quick C used to be very popular in the
C compiler market These days, an ANSI-compliant C compiler is usually part of anycommercially available C++ development package, such as Microsoft Visual C++ Inaddition, development packages come with an integrated development environment(IDE), which you can use to edit, compile, run, and debug your C programs all from thesame window
You can pick up any C compiler you like to compile the sample code given in the book,
as long as the compiler is ANSI C compliant You shouldn’t have problems installing a Ccompiler on your computer if you read the manuals that come with the compiler and fol-low the installation instructions correctly Most C and/or C++ compilers provide a quicktutorial that shows you how to install the compiler and set up a working developmentenvironment on your computer
These days, the Linux operating system is becoming more and more popular among PCusers In most cases, the Linux package you get contains a C compiler The C compilercan be installed on your PC when you’re installing the Linux operating system, or can beadded later after you finish the installation of Linux
A Sample C Programming Setup
I have a Pentium 100MHz PC with 32MB memory and with a 2.5GB hard drive (Thehard drive had about 1.5GB free space before I installed a copy of Microsoft Visual C++
5.0.) Also, I have Windows 95 as the operating system on the machine
In this book, all C programs are developed with Microsoft Visual C++ version 5.0 Thereasons I chose Visual C++ are simple: All C programs in this book are written in ANSI
C and can be compiled into console-mode applications (that is, text-based programs ning in a DOS window); the Visual C++ 5.0 package includes a good C compiler that isANSI C compliant
run-I set up my development environment in such a way that all C programs in this book can
be compiled and made into console applications Also, I test and run the applicationsmade from the C programs at a DOS prompt provided by Windows 95
In the following two sections, I’ll briefly show you how to use Microsoft’s and Boralnd’s
C compilers
Taking the First Step 17
1
Trang 39Using Microsoft’s Compiler
I’m going to show you how to use the C compiler that is bundled with the Microsoft’sVisual C++ package in this section If you need to learn more details on how to installVisual C++, please follow the instructions that come with the compiler
Now I assume you’ve installed a copy of Visual C++ 5.0 on your computer To start thecompiler, you can click the Start button from your Windows 95 (or 98 or NT), andchoose: Programs, Microsoft Visual C++ 5.0, Microsoft Visual C++ 5.0 Or, you cansimply run the application file MSDEV.EXEdirectly from the directory (folder) where youinstalled the Visual C++ package Figure 1.3 shows an example of the integrated devel-opment environment (IDE) from Visual C++ 5.0
F IGURE 1.3
An example of the IDE from Visual C++ ver- sion 5.0.
Then, you can open a new file within the IDE by clicking the New File button on the farleft side of the toolbar, and type the following text in the space of the new file:
#include <stdio.h>
main() { printf (“Howdy, neighbor! This is my first C program.\n”);
return 0;
}
Trang 40Figure 1.4 shows the IDE with the text you just typed in Don’t worry about the meaning
of the text In the next chapter, “Your First C Program,” will explain it to you
Taking the First Step 19
As dialog box, click the New Folder button and type in a name for your programmingfolder Then double-click that folder to open it, type MyFirstProgram.c in the File Namebox, and click Save Note that the extension .cis used to indicate that the file you justsaved is a C program file
Now, you need to click the Build menu and choose the Compile MyFirstProgram.coption By doing so, you ask the compiler to compile the text you just typed in and saved(see Figure 1.5) At this point, Visual C++ may prompt you to create a new workspace;
just click Yes and this will be done automatically There should be no errors or warnings
in the output window after the compiler is run
Then, click the Build menu again, and this time, choose the Build MyFirstProgram.exeoption which will eventually produce an executable file called MyFirstProgram.exe.Figure 1.6 shows that there are no errors or warnings after MyFirstProgram.exeis built