source e book of let us c by yashavant kanetkar
Let Us C
Fifth Edition
Yashavant P. Kanetkar
Dedicated to baba
Who couldn’t be here to see this day...
About the Author
Destiny drew Yashavant Kanetkar towards computers when the IT industry was just making a beginning in India. Having completed his education from VJTI Mumbai and IIT Kanpur in Mechanical Engineering he started his training company in Nagpur.
Yashavant has a passion for writing and is an author of several books in C, C++, VC++, C#, .NET, DirectX and COM programming. He is a much sought after speaker on various technology subjects and is a regular columnist for Express Computers and Developer 2.0. His current affiliations include being a Director of KICIT, a training company and DCube Software Technologies, a software development company. In recognition to his contribution Microsoft awarded him the prestigious “Best .NET Technical Contributor” award recently. He can be reached at kanetkar@kicit.com.
Acknowledgments
It has been a journey of almost a decade from the stage the book idea of “Let Us C” was conceived up to the release of this Fifth Edition. During this journey I have met so many students, developers, professors, publishers and authors who expressed their opinions about Let Us C. They have been the main motivators in my effort to continuously improve this book.
In particular I am indebted to Manish Jain who had a faith in this book idea, believed in my writing ability, whispered the words of encouragement and made helpful suggestions from time to time.
The five editions of this book saw several changes and facelifts. During this course people like Ajay Joshi, Amol Tambat, Ajay Daga, Nandita Shastri, Mrunal Khandekar and Rahul Bedge helped in writing programs, spotting bugs, drawing figures and preparing index. I trust that with their collective acumen all the programs would run correctly in all situations.
Anup Das, my colleague has a lot of influence on this Fifth Edition. He helped my clarify my thoughts and pointing me in the direction of Windows and Linux. He sincerely wanted this edition to offer “C, in today’s perspective”. I am hopeful that his dream has been realized.
I thank Seema, my wife, for her friendship and for her contributions in everything that I do in IT in ways more than she could ever guess. Though she is a Gynecologist by profession she has the uncanny ability to come up with suggestions that make me feel “Oh, why didn’t it occur to me”.
And finally my heartfelt gratitude to the countless students who made me look into every nook and cranny of C. I would forever remain indebted to them.. v
Preface to the Fifth Edition
It is mid 2004. World has left behind the DOTCOM bust, 9/11 tragedy, the economic downturn, etc. and moved on. Countless Indians have relentlessly worked for close to two decades to successfully establish “India” as a software brand. At times I take secret pleasure in seeing that a book that I have been part of, has contributed in its own little way in shaping so many budding careers that have made the “India” brand acceptable.
Computing and the way people use C for doing it keeps changing as years go by. So overwhelming has been the response to all the previous editions of “Let Us C” that I have now decided that each year I would come up with a new edition of it so that I can keep the readers abreast with the way C is being used at that point in time.
There are two phases in every C programmer’s life. In the first phase he is a learner trying to understand the language elements and their nuances. At this stage he wants a simple learning environment that helps him to master the language. In my opinion, even today there isn’t any learning environment that can beat Turbo C/C++ for simplicity. Hence the first fifteen chapters are written keeping this environment in mind, though a majority of these programs in these chapters would work with any C compiler.
Armed with the knowledge of language elements the C programmer enters the second phase. Here he wishes to use all that he has learnt to create programs that match the ability of programs that he see in today’s world. I am pointing towards programs in Windows and Linux world. Chapters 16 to 21 are devoted to this. I would like to your attention the fact that if you want to program Windows or Linux you need to have a very good grasp over the programming model used by each of these OS. Windows messaging architecture and Linux signaling mechanism are the cases in point. Once you understand these thoroughly rest is just a
vi
matter of time. Chapters 16 to 21 have been written with this motive.
In Linux programming the basic hurdle is in choosing the Linux distribution, compiler, editor, shell, libraries, etc. To get a head-start you can follow the choices that I found most reasonable and simple. They have been mentioned in Chapter 20 and Appendix H. Once you are comfortable you can explore other choices.
In fourth edition of Let Us C there were chapters on ‘Disk Basics’, ‘VDU Basics’, ‘Graphics’, ‘Mouse Programming’, ‘C and Assembly’. Though I used to like these chapters a lot I had to take a decision to drop them since most of them were DOS-centric and would not be so useful in modern-day programming. Modern counterparts of all of these have been covered in Chapters 16 to 21. However, if you still need the chapters from previous edition they are available at www.kicit.com/books/letusc/fourthedition.
Also, all the programs present in the book are available in source code form at www.kicit.com/books/letusc/sourcecode. You are free to download them, improve them, change them, do whatever with them. If you wish to get solutions for the Exercises in the book they are available in another book titled ‘Let Us C Solutions’.
‘Let Us C’ is as much your book as it is mine. So if you feel that I could have done certain job better than what I have, or you have any suggestions about what you would like to see in the next edition, please drop a line to letuscsuggestions@kicit.com.
All the best and happy programming!
vii
Contents
1.
2.
Getting Started 1
What is C 2
Getting Started with C 4
The C Character Set 5
Constants, Variables and Keywords 6
Types of C Constants 7
Rules for Constructing Integer Constants 8
Rules for Constructing Real Constants 9
Rules for Constructing Character Constants 10
Types of C Variables 11
Rules for Constructing Variable Names 11
C Keywords 12
The First C Program 13
Compilation and Execution 19
Receiving Input 21
C Instructions 23
Type Declaration Instruction 24
Arithmetic Instruction 25
Integer and Float Conversions 29
Type Conversion in Assignments 29
Hierarchy of Operations 31
Associativity of Operators 34
Control Instructions in C 37
Summary 37
Exercise 38
The Decision Control Structure 49
Decisions! Decisions! 50
The if Statement 51
The Real Thing 55
Multiple Statements within if 56
The if-else Statement 58
viii
Nested if-elses 61
Forms of if 62
Use of Logical Operators 64
The else if Clause 66
The ! Operator 72
Hierarchy of Operators Revisited 73
A Word of Caution 73
The Conditional Operators 76
Summary 77
Exercise 78
3.
4.
The Loop Control Structure 97
Loops 98
The while Loop 99
Tips and Traps 101
More Operators 105
The for Loop 107
Nesting of Loops 114
Multiple Initialisations in the for Loop 115
The Odd Loop 116
The break Statement 118
The continue Statement 120
The do-while Loop 121
Summary 124
Exercise 124
The Case Control Structure 135
Decisions Using switch 136
The Tips and Traps 140
switch Versus if-else Ladder 144
The goto Keyword 145
Summary 148
Exercise 149
ix
5.
6.
Functions & Pointers 157
What is a Function 158
Why Use Functions 165
Passing Values between Functions 166
Scope Rule of Functions 171
Calling Convention 172
One Dicey Issue 173
Advanced Features of Functions 174
Function Declaration and Prototypes 175
Call by Value and Call by Reference 178
An Introduction to Pointers 178
Pointer Notation 179
Back to Function Calls 186
Conclusions 189
Recursion 189
Recursion and Stack 194
Adding Functions to the Library 197
Summary 201
Exercise 201
Data Types Revisited 213
Integers, long and short 214
Integers, signed and unsigned 216
Chars, signed and unsigned 217
Floats and Doubles 219
A Few More Issues… 221
Storage Classes in C 223
Automatic Storage Class 224
Register Storage Class 226
Static Storage Class 227
External Storage Class 230
Which to Use When 233
Summary 234
Exercise 235
x
The C Preprocessor 241
Features of C Preprocessor 242
Macro Expansion 244
Macros with Arguments 248
Macros versus Functions 252
File Inclusion 253
Conditional Compilation 255
#if and #elif Directives 258
Miscellaneous Directives 260
#undef Directive 260
#pragma Directive 261
Summary 263
Exercise 264
7.
8.
Arrays 269
What are Arrays 270
A Simple Program Using Array 272
More on Arrays 275
Array Initialization 275
Bounds Checking 276
Passing Array Elements to a Function 277
Pointers and Arrays 279
Passing an Entire Array to a Function 286
The Real Thing 287
Two Dimensional Arrays 289
Initializing a 2-Dimensional Array 290
Memory Map of a 2-Dimensional Array 291
Pointers and 2-Dimensional Arrays 292
Pointer to an Array 295
Passing 2-D array to a Function 297
Array of Pointers 300
Three Dimensional Array 302
Summary 304
xi
Exercise 304
Puppetting On Strings 327
What are Strings 328
More about Strings 329
Pointers and Strings 334
Standard Library String Functions 335
strlen( ) 337
strcpy( ) 339
strcat( ) 342
strcmp( ) 343
Two-Dimensional Array of Characters 344
Array of Pointers to Strings 347
Limitation of Array of Pointers to Strings 351
Solution 352
Summary 353
Exercise 354
9.
10.
11.
Structures 363
Why Use Structures 364
Declaring a Structure 367
Accessing Structure Elements 370
How Structure Elements are Stored 370
Array of Structures 371
Additional Features of Structures 374
Uses of Structures 383
Summary 384
Exercise 384
Console Input/Output 393
Types of I/O 394
Console I/O Functions 395
Formatted Console I/O Functions 396
xii
sprintf( ) and sscanf( ) Functions 404
Unformatted Console I/O Functions 405
Summary 409
Exercise 409
File Input/Output 415
Data Organization 416
File Operations 417
Opening a File 418
Reading from a File 420
Trouble in Opening a File 421
Closing the File 422
Counting Characters, Tabs, Spaces, … 422
A File-copy Program 424
Writing to a File 425
File Opening Modes 426
String (line) I/O in Files 427
The Awkward Newline 430
Record I/O in Files 430
Text Files and Binary Files 434
Record I/O Revisited 437
Database Management 441
Low Level Disk I/O 447
A Low Level File-copy Program 448
I/O Under Windows 453
Summary 453
Exercise 454
12.
13.
More Issues In Input/Output 465
Using argc and argv 466
Detecting Errors in Reading/Writing 470
Standard I/O Devices 472
I/O Redirection 473
Redirecting the Output 474
xiii
Redirecting the Input 476
Both Ways at Once 477
Summary 478
Exercise 478
14.
15.
Operations On Bits 481
Bitwise Operators 482
One’s Complement Operator 484
Right Shift Operator 486
Left Shift Operator 488
Bitwise AND Operator 493
Bitwise OR Operator 498
Bitwise XOR Operator 499
The showbits( ) Function 500
Summary 501
Exercise 501
Miscellaneous Features 505
Enumerated Data Type 506
Uses of Enumerated Data Type 507
Renaming Data Types with typedef 510
Typecasting 511
Bit Fields 513
Pointers to Functions 515
Functions Returning Pointers 518
Functions with Variable Number of Arguments 520
Unions 524
Union of Structures 530
Summary 531
Exercise 531
xiv
C Under Windows 535
Which Windows… 536
Integers 537
The Use of typedef 537
Pointers in the 32-bit World 539
Memory Management 540
Device Access 543
DOS Programming Model 543
Windows Programming Model 547
Event Driven Model 551
Windows Programming, a Closer Look 552
The First Windows Program 554
Hungarian Notation 558
Summary 558
Exercise 559
16.
17.
18.
Windows Programming 561
The Role of a Message Box 562
Here Comes the window… 563
More Windows 566
A Real-World Window 567
Creation and Displaying of Window 569
Interaction with Window 570
Reacting to Messages 572
Program Instances 575
Summary 575
Exercise 576
Graphics Under Windows 579
Graphics as of Now 580
Device Independent Drawing 580
xv
Hello Windows 582
Drawing Shapes 586
Types of Pens 590
Types of Brushes 592
Code and Resources 596
Freehand Drawing, the Paintbrush Style 596
Capturing the Mouse 600
Device Context, a Closer Look 601
Displaying a Bitmap 603
Animation at Work 607
WM_CREATE and OnCreate( ) 611
WM_TIMER and OnTimer( ) 611
A Few More Points… 612
Windows, the Endless World… 613
Summary 614
Exercise 615
19.
Interaction With Hardware 617
Hardware Interaction 618
Hardware Interaction, DOS Perspective 619
Hardware Interaction, Windows Perspective 623
Communication with Storage Devices 626
The ReadSector( ) Function 631
Accessing Other Storage Devices 633
Communication with Keyboard 634
Dynamic Linking 635
Windows Hooks 635
Caps Locked, Permanently 637
Did You Press It TTwwiiccee…… 643
Mangling Keys 644
KeyLogger 645
Where is This Leading 646
Summary 647
Exercise 647
xvi
C Under Linux 649
What is Linux 650
C Programming Under Linux 651
The ‘Hello Linux’ Program 652
Processes 653
Parent and Child Processes 655
More Processes 659
Zombies and Orphans 660
One Interesting Fact 663
Summary 664
Exercise 664
20.
21.
More Linux Programming 667
Communication using Signals 668
Handling Multiple Signals 671
Registering a Common Handler 673
Blocking Signals 675
Event Driven Programming 678
Where Do You Go From Here 684
Summary 684
Exercise 685
Appendix A – Precedence Table 687
Appendix B – Standard Library Functions 691
Appendix C – Chasing the Bugs 701
Appendix D – Hexadecimal Numbering 713
Appendix E – ASCII Chart 719
Appendix F – Helper.h File 725
Appendix G – Boot Parameters 729
Appendix H – Linux Installation 735
Index 739
xvii
1 Getting Started
• What is C
• Getting Started with C
The C Character Set
Constants, Variables and Keywords
Types of C Constants
Rules for Constructing Integer Constants
Rules for Constructing Real Constants
Rules for Constructing Character Constants
Types of C Variables
Rules for Constructing Variable Names
C Keywords
• The First C Program
• Compilation and Execution
• Receiving Input
• C Instructions
Type Declaration Instruction
Arithmetic Instruction
Integer and Float Conversions
Hierarchy of Operations
Associativity Of Operators
• Control Instruction in C
• Summary
• Exercise
1
2 Let Us C
efore we can begin to write serious programs in C, it would be interesting to find out what really is C, how it came into existence and how does it compare with other computer languages. In this chapter we would briefly outline these issues. B
Four important aspects of any language are the way it stores data, the way it operates upon this data, how it accomplishes input and output and how it lets you control the sequence of execution of instructions in a program. We would discuss the first three of these building blocks in this chapter.
What is C
C is a programming language developed at AT & T’s Bell Laboratories of USA in 1972. It was designed and written by a man named Dennis Ritchie. In the late seventies C began to replace the more familiar languages of that time like PL/I, ALGOL, etc. No one pushed C. It wasn’t made the ‘official’ Bell Labs language. Thus, without any advertisement C’s reputation spread and its pool of users grew. Ritchie seems to have been rather surprised that so many programmers preferred C to older languages like FORTRAN or PL/I, or the newer ones like Pascal and APL. But, that's what happened.
Possibly why C seems so popular is because it is reliable, simple and easy to use. Moreover, in an industry where newer languages, tools and technologies emerge and vanish day in and day out, a language that has survived for more than 3 decades has to be really good.
An opinion that is often heard today is – “C has been already superceded by languages like C++, C# and Java, so why bother to
Chapter 1: Getting Started 3
learn C today”. I seriously beg to differ with this opinion. There are several reasons for this:
(a)
(b)
(c)
(d)
I believe that nobody can learn C++ or Java directly. This is because while learning these languages you have things like classes, objects, inheritance, polymorphism, templates, exception handling, references, etc. do deal with apart from knowing the actual language elements. Learning these complicated concepts when you are not even comfortable with the basic language elements is like putting the cart before the horse. Hence one should first learn all the language elements very thoroughly using C language before migrating to C++, C# or Java. Though this two step learning process may take more time, but at the end of it you will definitely find it worth the trouble.
C++, C# or Java make use of a principle called Object Oriented Programming (OOP) to organize the program. This organizing principle has lots of advantages to offer. But even while using this organizing principle you would still need a good hold over the language elements of C and the basic programming skills.
Though many C++ and Java based programming tools and frameworks have evolved over the years the importance of C is still unchallenged because knowingly or unknowingly while using these frameworks and tools you would be still required to use the core C language elements—another good reason why one should learn C before C++, C# or Java.
Major parts of popular operating systems like Windows, UNIX, Linux is still written in C. This is because even today when it comes to performance (speed of execution) nothing beats C. Moreover, if one is to extend the operating system to work with new devices one needs to write device driver programs. These programs are exclusively written in C.
4 Let Us C
(e)
(f)
(g)
Mobile devices like cellular phones and palmtops are becoming increasingly popular. Also, common consumer devices like microwave oven, washing machines and digital cameras are getting smarter by the day. This smartness comes from a microprocessor, an operating system and a program embedded in this devices. These programs not only have to run fast but also have to work in limited amount of memory. No wonder that such programs are written in C. With these constraints on time and space, C is the language of choice while building such operating systems and programs.
You must have seen several professional 3D computer games where the user navigates some object, like say a spaceship and fires bullets at the invaders. The essence of all such games is speed. Needless to say, such games won't become popular if they takes a long time to move the spaceship or to fire a bullet. To match the expectations of the player the game has to react fast to the user inputs. This is where C language scores over other languages. Many popular gaming frameworks have been built using C language.
At times one is required to very closely interact with the hardware devices. Since C provides several language elements that make this interaction feasible without compromising the performance it is the preferred choice of the programmer.
I hope that these are very convincing reasons why one should adopt C as the first and the very important step in your quest for learning programming languages.
Getting Started with C
Communicating with a computer involves speaking the language the computer understands, which immediately rules out English as the language of communication with computer. However, there is
Chapter 1: Getting Started 5
a close analogy between learning English language and learning C language. The classical method of learning English is to first learn the alphabets used in the language, then learn to combine these alphabets to form words, which in turn are combined to form sentences and sentences are combined to form paragraphs. Learning C is similar and easier. Instead of straight-away learning how to write programs, we must first know what alphabets, numbers and special symbols are used in C, then how using them constants, variables and keywords are constructed, and finally how are these combined to form an instruction. A group of instructions would be combined later on to form a program. This is illustrated in the Figure 1.1.
Alphabets
Words
Sentences
Paragraphs
Alphabets Digits Special sy- mbols
Constants Variables Keywords
Instructions
Program
Steps in learning English language:
Steps in learning C:
Figure 1.1
The C Character Set
A character denotes any alphabet, digit or special symbol used to represent information. Figure 1.2 shows the valid alphabets, numbers and special symbols allowed in C.
6 Let Us C
Alphabets
A, B, ….., Y, Z
a, b, ……, y, z
Digits
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special symbols
~ ‘ ! @ # % ^ & * ( ) _ - + = | \ { }
[ ] : ; " ' < > , . ? /
Figure 1.2
Constants, Variables and Keywords
The alphabets, numbers and special symbols when properly combined form constants, variables and keywords. Let us see what are ‘constants’ and ‘variables’ in C. A constant is an entity that doesn’t change whereas a variable is an entity that may change.
In any program we typically do lots of calculations. The results of these calculations are stored in computers memory. Like human memory the computer memory also consists of millions of cells. The calculated values are stored in these memory cells. To make the retrieval and usage of these values easy these memory cells (also called memory locations) are given names. Since the value stored in each location may change the names given to these locations are called variable names. Consider the following example.
Here 3 is stored in a memory location and a name x is given to it. Then we are assigning a new value 5 to the same memory location x. This would overwrite the earlier value 3, since a memory location can hold only one value at a time. This is shown in Figure 1.3.
Chapter 1: Getting Started 7
x = 3 x = 5
Figure 1.3
x 3
x 5
Since the location whose name is x can hold different values at different times x is known as a variable. As against this, 3 or 5 do not change, hence are known as constants.
Types of C Constants
C constants can be divided into two major categories:
(a)
(b)
Primary Constants
Secondary Constants
These constants are further categorized as shown in Figure 1.4.
8 Let Us C
Figure 1.4 C Constants
Primary Constants
Secondary Constants
Integer Constant
Real Constant
Character Constant
Array
Pointer
Structure
Union
Enum,etc.
At this stage we would restrict our discussion to only Primary Constants, namely, Integer, Real and Character constants. Let us see the details of each of these constants. For constructing these different types of constants certain rules have been laid down. These rules are as under:
Rules for Constructing Integer Constants
An integer constant must have at least one digit. (a)
(b)
(c)
(d)
(e)
(f)
It must not have a decimal point.
It can be either positive or negative.
If no sign precedes an integer constant it is assumed to be positive.
No commas or blanks are allowed within an integer constant.
The allowable range for integer constants is -32768 to 32767.
Truly speaking the range of an Integer constant depends upon the compiler. For a 16-bit compiler like Turbo C or Turbo C++ the
Chapter 1: Getting Started 9
range is –32768 to 32767. For a 32-bit compiler the range would be even greater. Question like what exactly do you mean by a 16-bit or a 32-bit compiler, what range of an Integer constant has to do with the type of compiler and such questions are discussed in detail in Chapter 16. Till that time it would be assumed that we are working with a 16-bit compiler.
Ex.: 426
+782
-8000
-7605
Rules for Constructing Real Constants
Real constants are often called Floating Point constants. The real constants could be written in two forms—Fractional form and Exponential form.
Following rules must be observed while constructing real constants expressed in fractional form:
(a)
(b)
(c)
(d)
(e)
A real constant must have at least one digit.
It must have a decimal point.
It could be either positive or negative.
Default sign is positive.
No commas or blanks are allowed within a real constant.
Ex.: +325.34
426.0
-32.76
-48.5792
The exponential form of representation of real constants is usually used if the value of the constant is either too small or too large. It however doesn’t restrict us in any way from using exponential form of representation for other real constants.
10 Let Us C
In exponential form of representation, the real constant is represented in two parts. The part appearing before ‘e’ is called mantissa, whereas the part following ‘e’ is called exponent.
Following rules must be observed while constructing real constants expressed in exponential form:
(a)
(b)
(c)
(d)
(e)
(a)
(b)
The mantissa part and the exponential part should be separated by a letter e.
The mantissa part may have a positive or negative sign.
Default sign of mantissa part is positive.
The exponent must have at least one digit, which must be a positive or negative integer. Default sign is positive.
Range of real constants expressed in exponential form is -3.4e38 to 3.4e38.
Ex.: +3.2e-5
4.1e8
-0.2e+3
-3.2e-5
Rules for Constructing Character Constants
A character constant is a single alphabet, a single digit or a single special symbol enclosed within single inverted commas. Both the inverted commas should point to the left. For example, ’A’ is a valid character constant whereas ‘A’ is not.
The maximum length of a character constant can be 1 character.
Ex.: 'A'
'I'
'5'
'='
Chapter 1: Getting Started 11
Types of C Variables
As we saw earlier, an entity that may vary during program execution is called a variable. Variable names are names given to locations in memory. These locations can contain integer, real or character constants. In any language, the types of variables that it can support depend on the types of constants that it can handle. This is because a particular type of variable can hold only the same type of constant. For example, an integer variable can hold only an integer constant, a real variable can hold only a real constant and a character variable can hold only a character constant.
The rules for constructing different types of constants are different. However, for constructing variable names of all types the same set of rules apply. These rules are given below.
Rules for Constructing Variable Names
(a)
(b)
(c)
(d)
A variable name is any combination of 1 to 31 alphabets, digits or underscores. Some compilers allow variable names whose length could be up to 247 characters. Still, it would be safer to stick to the rule of 31 characters. Do not create unnecessarily long variable names as it adds to your typing effort.
The first character in the variable name must be an alphabet or underscore.
No commas or blanks are allowed within a variable name.
No special symbol other than an underscore (as in gross_sal) can be used in a variable name.
Ex.: si_int
m_hra
pop_e_89
These rules remain same for all the types of primary and secondary variables. Naturally, the question follows... how is C able to differentiate between these variables? This is a rather simple
12 Let Us C
matter. C compiler is able to distinguish between the variable names by making it compulsory for you to declare the type of any variable name that you wish to use in a program. This type declaration is done at the beginning of the program. Following are the examples of type declaration statements:
Ex.: int si, m_hra ;
float bassal ;
char code ;
Since, the maximum allowable length of a variable name is 31 characters, an enormous number of variable names can be constructed using the above-mentioned rules. It is a good practice to exploit this enormous choice in naming variables by using meaningful variable names.
Thus, if we want to calculate simple interest, it is always advisable to construct meaningful variable names like prin, roi, noy to represent Principle, Rate of interest and Number of years rather than using the variables a, b, c.
C Keywords
Keywords are the words whose meaning has already been explained to the C compiler (or in a broad sense to the computer). The keywords cannot be used as variable names because if we do so we are trying to assign a new meaning to the keyword, which is not allowed by the computer. Some C compilers allow you to construct variable names that exactly resemble the keywords. However, it would be safer not to mix up the variable names and the keywords. The keywords are also called ‘Reserved words’.
There are only 32 keywords available in C. Figure 1.5 gives a list of these keywords for your ready reference. A detailed discussion of each of these keywords would be taken up in later chapters wherever their use is relevant.
Chapter 1: Getting Started 13
auto
double
int
struct
break
else
long
switch
case
enum
register
typedef
char
extern
return
union
const
float
short
unsigned
continue
for
signed
void
default
goto
sizeof
volatile
do
if
static
while
Figure 1.5
Note that compiler vendors (like Microsoft, Borland, etc.) provide their own keywords apart from the ones mentioned above. These include extended keywords like near, far, asm, etc. Though it has been suggested by the ANSI committee that every such compiler specific keyword should be preceded by two underscores (as in __asm ), not every vendor follows this rule.
The First C Program
Armed with the knowledge about the types of variables, constants & keywords the next logical step is to combine them to form instructions. However, instead of this, we would write our first C program now. Once we have done that we would see in detail the instructions that it made use of.
Before we begin with our first C program do remember the following rules that are applicable to all C programs:
(a)
Each instruction in a C program is written as a separate statement. Therefore a complete C program would comprise of a series of statements.
14 Let Us C
(b)
(c)
(d)
(e)
(f)
The statements in a program must appear in the same order in which we wish them to be executed; unless of course the logic of the problem demands a deliberate ‘jump’ or transfer of control to a statement, which is out of sequence.
Blank spaces may be inserted between two words to improve the readability of the statement. However, no blank spaces are allowed within a variable, constant or keyword.
All statements are entered in small case letters.
C has no specific rules for the position at which a statement is to be written. That’s why it is often called a free-form language.
Every C statement must end with a ;. Thus ; acts as a statement terminator.
Let us now write down our first C program. It would simply calculate simple interest for a set of values representing principle, number of years and rate of interest.
/* Calculation of simple interest */
/* Author gekay Date: 25/05/2004 */
main( )
{
int p, n ;
float r, si ;
p = 1000 ;
n = 3 ;
r = 8.5 ;
/* formula for simple interest */
si = p * n * r / 100 ;
printf ( "%f" , si ) ;
Chapter 1: Getting Started 15
}
Now a few useful tips about the program...
− Comment about the program should be enclosed within /* */. For example, the first two statements in our program are comments.
− Though comments are not necessary, it is a good practice to begin a program with a comment indicating the purpose of the program, its author and the date on which the program was written.
− Any number of comments can be written at any place in the program. For example, a comment can be written before the statement, after the statement or within the statement as shown below:
/* formula */ si = p * n * r / 100 ;
si = p * n * r / 100 ; /* formula */
si = p * n * r / /* formula */ 100 ;
− Sometimes it is not so obvious as to what a particular statement in a program accomplishes. At such times it is worthwhile mentioning the purpose of the statement (or a set of statements) using a comment. For example:
/* formula for simple interest */
si = p * n * r / 100 ;
− Often programmers seem to ignore writing of comments. But when a team is building big software well commented code is almost essential for other team members to understand it.
16 Let Us C
− Although a lot of comments are probably not necessary in this program, it is usually the case that programmers tend to use too few comments rather than too many. An adequate number of comments can save hours of misery and suffering when you later try to figure out what the program does.
− The normal language rules do not apply to text written within /* .. */. Thus we can type this text in small case, capital or a combination. This is because the comments are solely given for the understanding of the programmer or the fellow programmers and are completely ignored by the compiler.
− Comments cannot be nested. For example,
/* Cal of SI /* Author sam date 01/01/2002 */ */
is invalid.
− A comment can be split over more than one line, as in,
/* This is
a jazzy
comment */
Such a comment is often called a multi-line comment.
− main( ) is a collective name given to a set of statements. This name has to be main( ), it cannot be anything else. All statements that belong to main( ) are enclosed within a pair of braces { } as shown below.
main( )
{
statement 1 ;
statement 2 ;
Chapter 1: Getting Started 17
statement 3 ;
}
− Technically speaking main( ) is a function. Every function has a pair of parentheses ( ) associated with it. We would discuss functions and their working in great detail in Chapter 5.
− Any variable used in the program must be declared before using it. For example,
int p, n ;
float r, si ;
− Any C statement always ends with a ;
For example,
float r, si ;
r = 8.5 ;
− In the statement,
si = p * n * r / 100 ;
* and / are the arithmetic operators. The arithmetic operators available in C are +, -, * and /. C is very rich in operators. There are about 45 operators available in C. Surprisingly there is no operator for exponentiation... a slip, which can be forgiven considering the fact that C has been developed by an individual, not by a committee.
− Once the value of si is calculated it needs to be displayed on the screen. Unlike other languages, C does not contain any instruction to display output on the screen. All output to screen is achieved using readymade library functions. One such
18 Let Us C
function is printf( ). We have used it display on the screen the value contained in si.
The general form of printf( ) function is,
printf ( "",
Let Us C
Fifth Edition
Yashavant P. Kanetkar
Dedicated to baba
Who couldn’t be here to see this day...
About the Author
Destiny drew Yashavant Kanetkar towards computers when the IT industry was just making a beginning in India. Having completed his education from VJTI Mumbai and IIT Kanpur in Mechanical Engineering he started his training company in Nagpur.
Yashavant has a passion for writing and is an author of several books in C, C++, VC++, C#, .NET, DirectX and COM programming. He is a much sought after speaker on various technology subjects and is a regular columnist for Express Computers and Developer 2.0. His current affiliations include being a Director of KICIT, a training company and DCube Software Technologies, a software development company. In recognition to his contribution Microsoft awarded him the prestigious “Best .NET Technical Contributor” award recently. He can be reached at kanetkar@kicit.com.
Acknowledgments
It has been a journey of almost a decade from the stage the book idea of “Let Us C” was conceived up to the release of this Fifth Edition. During this journey I have met so many students, developers, professors, publishers and authors who expressed their opinions about Let Us C. They have been the main motivators in my effort to continuously improve this book.
In particular I am indebted to Manish Jain who had a faith in this book idea, believed in my writing ability, whispered the words of encouragement and made helpful suggestions from time to time.
The five editions of this book saw several changes and facelifts. During this course people like Ajay Joshi, Amol Tambat, Ajay Daga, Nandita Shastri, Mrunal Khandekar and Rahul Bedge helped in writing programs, spotting bugs, drawing figures and preparing index. I trust that with their collective acumen all the programs would run correctly in all situations.
Anup Das, my colleague has a lot of influence on this Fifth Edition. He helped my clarify my thoughts and pointing me in the direction of Windows and Linux. He sincerely wanted this edition to offer “C, in today’s perspective”. I am hopeful that his dream has been realized.
I thank Seema, my wife, for her friendship and for her contributions in everything that I do in IT in ways more than she could ever guess. Though she is a Gynecologist by profession she has the uncanny ability to come up with suggestions that make me feel “Oh, why didn’t it occur to me”.
And finally my heartfelt gratitude to the countless students who made me look into every nook and cranny of C. I would forever remain indebted to them.. v
Preface to the Fifth Edition
It is mid 2004. World has left behind the DOTCOM bust, 9/11 tragedy, the economic downturn, etc. and moved on. Countless Indians have relentlessly worked for close to two decades to successfully establish “India” as a software brand. At times I take secret pleasure in seeing that a book that I have been part of, has contributed in its own little way in shaping so many budding careers that have made the “India” brand acceptable.
Computing and the way people use C for doing it keeps changing as years go by. So overwhelming has been the response to all the previous editions of “Let Us C” that I have now decided that each year I would come up with a new edition of it so that I can keep the readers abreast with the way C is being used at that point in time.
There are two phases in every C programmer’s life. In the first phase he is a learner trying to understand the language elements and their nuances. At this stage he wants a simple learning environment that helps him to master the language. In my opinion, even today there isn’t any learning environment that can beat Turbo C/C++ for simplicity. Hence the first fifteen chapters are written keeping this environment in mind, though a majority of these programs in these chapters would work with any C compiler.
Armed with the knowledge of language elements the C programmer enters the second phase. Here he wishes to use all that he has learnt to create programs that match the ability of programs that he see in today’s world. I am pointing towards programs in Windows and Linux world. Chapters 16 to 21 are devoted to this. I would like to your attention the fact that if you want to program Windows or Linux you need to have a very good grasp over the programming model used by each of these OS. Windows messaging architecture and Linux signaling mechanism are the cases in point. Once you understand these thoroughly rest is just a
vi
matter of time. Chapters 16 to 21 have been written with this motive.
In Linux programming the basic hurdle is in choosing the Linux distribution, compiler, editor, shell, libraries, etc. To get a head-start you can follow the choices that I found most reasonable and simple. They have been mentioned in Chapter 20 and Appendix H. Once you are comfortable you can explore other choices.
In fourth edition of Let Us C there were chapters on ‘Disk Basics’, ‘VDU Basics’, ‘Graphics’, ‘Mouse Programming’, ‘C and Assembly’. Though I used to like these chapters a lot I had to take a decision to drop them since most of them were DOS-centric and would not be so useful in modern-day programming. Modern counterparts of all of these have been covered in Chapters 16 to 21. However, if you still need the chapters from previous edition they are available at www.kicit.com/books/letusc/fourthedition.
Also, all the programs present in the book are available in source code form at www.kicit.com/books/letusc/sourcecode. You are free to download them, improve them, change them, do whatever with them. If you wish to get solutions for the Exercises in the book they are available in another book titled ‘Let Us C Solutions’.
‘Let Us C’ is as much your book as it is mine. So if you feel that I could have done certain job better than what I have, or you have any suggestions about what you would like to see in the next edition, please drop a line to letuscsuggestions@kicit.com.
All the best and happy programming!
vii
Contents
1.
2.
Getting Started 1
What is C 2
Getting Started with C 4
The C Character Set 5
Constants, Variables and Keywords 6
Types of C Constants 7
Rules for Constructing Integer Constants 8
Rules for Constructing Real Constants 9
Rules for Constructing Character Constants 10
Types of C Variables 11
Rules for Constructing Variable Names 11
C Keywords 12
The First C Program 13
Compilation and Execution 19
Receiving Input 21
C Instructions 23
Type Declaration Instruction 24
Arithmetic Instruction 25
Integer and Float Conversions 29
Type Conversion in Assignments 29
Hierarchy of Operations 31
Associativity of Operators 34
Control Instructions in C 37
Summary 37
Exercise 38
The Decision Control Structure 49
Decisions! Decisions! 50
The if Statement 51
The Real Thing 55
Multiple Statements within if 56
The if-else Statement 58
viii
Nested if-elses 61
Forms of if 62
Use of Logical Operators 64
The else if Clause 66
The ! Operator 72
Hierarchy of Operators Revisited 73
A Word of Caution 73
The Conditional Operators 76
Summary 77
Exercise 78
3.
4.
The Loop Control Structure 97
Loops 98
The while Loop 99
Tips and Traps 101
More Operators 105
The for Loop 107
Nesting of Loops 114
Multiple Initialisations in the for Loop 115
The Odd Loop 116
The break Statement 118
The continue Statement 120
The do-while Loop 121
Summary 124
Exercise 124
The Case Control Structure 135
Decisions Using switch 136
The Tips and Traps 140
switch Versus if-else Ladder 144
The goto Keyword 145
Summary 148
Exercise 149
ix
5.
6.
Functions & Pointers 157
What is a Function 158
Why Use Functions 165
Passing Values between Functions 166
Scope Rule of Functions 171
Calling Convention 172
One Dicey Issue 173
Advanced Features of Functions 174
Function Declaration and Prototypes 175
Call by Value and Call by Reference 178
An Introduction to Pointers 178
Pointer Notation 179
Back to Function Calls 186
Conclusions 189
Recursion 189
Recursion and Stack 194
Adding Functions to the Library 197
Summary 201
Exercise 201
Data Types Revisited 213
Integers, long and short 214
Integers, signed and unsigned 216
Chars, signed and unsigned 217
Floats and Doubles 219
A Few More Issues… 221
Storage Classes in C 223
Automatic Storage Class 224
Register Storage Class 226
Static Storage Class 227
External Storage Class 230
Which to Use When 233
Summary 234
Exercise 235
x
The C Preprocessor 241
Features of C Preprocessor 242
Macro Expansion 244
Macros with Arguments 248
Macros versus Functions 252
File Inclusion 253
Conditional Compilation 255
#if and #elif Directives 258
Miscellaneous Directives 260
#undef Directive 260
#pragma Directive 261
Summary 263
Exercise 264
7.
8.
Arrays 269
What are Arrays 270
A Simple Program Using Array 272
More on Arrays 275
Array Initialization 275
Bounds Checking 276
Passing Array Elements to a Function 277
Pointers and Arrays 279
Passing an Entire Array to a Function 286
The Real Thing 287
Two Dimensional Arrays 289
Initializing a 2-Dimensional Array 290
Memory Map of a 2-Dimensional Array 291
Pointers and 2-Dimensional Arrays 292
Pointer to an Array 295
Passing 2-D array to a Function 297
Array of Pointers 300
Three Dimensional Array 302
Summary 304
xi
Exercise 304
Puppetting On Strings 327
What are Strings 328
More about Strings 329
Pointers and Strings 334
Standard Library String Functions 335
strlen( ) 337
strcpy( ) 339
strcat( ) 342
strcmp( ) 343
Two-Dimensional Array of Characters 344
Array of Pointers to Strings 347
Limitation of Array of Pointers to Strings 351
Solution 352
Summary 353
Exercise 354
9.
10.
11.
Structures 363
Why Use Structures 364
Declaring a Structure 367
Accessing Structure Elements 370
How Structure Elements are Stored 370
Array of Structures 371
Additional Features of Structures 374
Uses of Structures 383
Summary 384
Exercise 384
Console Input/Output 393
Types of I/O 394
Console I/O Functions 395
Formatted Console I/O Functions 396
xii
sprintf( ) and sscanf( ) Functions 404
Unformatted Console I/O Functions 405
Summary 409
Exercise 409
File Input/Output 415
Data Organization 416
File Operations 417
Opening a File 418
Reading from a File 420
Trouble in Opening a File 421
Closing the File 422
Counting Characters, Tabs, Spaces, … 422
A File-copy Program 424
Writing to a File 425
File Opening Modes 426
String (line) I/O in Files 427
The Awkward Newline 430
Record I/O in Files 430
Text Files and Binary Files 434
Record I/O Revisited 437
Database Management 441
Low Level Disk I/O 447
A Low Level File-copy Program 448
I/O Under Windows 453
Summary 453
Exercise 454
12.
13.
More Issues In Input/Output 465
Using argc and argv 466
Detecting Errors in Reading/Writing 470
Standard I/O Devices 472
I/O Redirection 473
Redirecting the Output 474
xiii
Redirecting the Input 476
Both Ways at Once 477
Summary 478
Exercise 478
14.
15.
Operations On Bits 481
Bitwise Operators 482
One’s Complement Operator 484
Right Shift Operator 486
Left Shift Operator 488
Bitwise AND Operator 493
Bitwise OR Operator 498
Bitwise XOR Operator 499
The showbits( ) Function 500
Summary 501
Exercise 501
Miscellaneous Features 505
Enumerated Data Type 506
Uses of Enumerated Data Type 507
Renaming Data Types with typedef 510
Typecasting 511
Bit Fields 513
Pointers to Functions 515
Functions Returning Pointers 518
Functions with Variable Number of Arguments 520
Unions 524
Union of Structures 530
Summary 531
Exercise 531
xiv
C Under Windows 535
Which Windows… 536
Integers 537
The Use of typedef 537
Pointers in the 32-bit World 539
Memory Management 540
Device Access 543
DOS Programming Model 543
Windows Programming Model 547
Event Driven Model 551
Windows Programming, a Closer Look 552
The First Windows Program 554
Hungarian Notation 558
Summary 558
Exercise 559
16.
17.
18.
Windows Programming 561
The Role of a Message Box 562
Here Comes the window… 563
More Windows 566
A Real-World Window 567
Creation and Displaying of Window 569
Interaction with Window 570
Reacting to Messages 572
Program Instances 575
Summary 575
Exercise 576
Graphics Under Windows 579
Graphics as of Now 580
Device Independent Drawing 580
xv
Hello Windows 582
Drawing Shapes 586
Types of Pens 590
Types of Brushes 592
Code and Resources 596
Freehand Drawing, the Paintbrush Style 596
Capturing the Mouse 600
Device Context, a Closer Look 601
Displaying a Bitmap 603
Animation at Work 607
WM_CREATE and OnCreate( ) 611
WM_TIMER and OnTimer( ) 611
A Few More Points… 612
Windows, the Endless World… 613
Summary 614
Exercise 615
19.
Interaction With Hardware 617
Hardware Interaction 618
Hardware Interaction, DOS Perspective 619
Hardware Interaction, Windows Perspective 623
Communication with Storage Devices 626
The ReadSector( ) Function 631
Accessing Other Storage Devices 633
Communication with Keyboard 634
Dynamic Linking 635
Windows Hooks 635
Caps Locked, Permanently 637
Did You Press It TTwwiiccee…… 643
Mangling Keys 644
KeyLogger 645
Where is This Leading 646
Summary 647
Exercise 647
xvi
C Under Linux 649
What is Linux 650
C Programming Under Linux 651
The ‘Hello Linux’ Program 652
Processes 653
Parent and Child Processes 655
More Processes 659
Zombies and Orphans 660
One Interesting Fact 663
Summary 664
Exercise 664
20.
21.
More Linux Programming 667
Communication using Signals 668
Handling Multiple Signals 671
Registering a Common Handler 673
Blocking Signals 675
Event Driven Programming 678
Where Do You Go From Here 684
Summary 684
Exercise 685
Appendix A – Precedence Table 687
Appendix B – Standard Library Functions 691
Appendix C – Chasing the Bugs 701
Appendix D – Hexadecimal Numbering 713
Appendix E – ASCII Chart 719
Appendix F – Helper.h File 725
Appendix G – Boot Parameters 729
Appendix H – Linux Installation 735
Index 739
xvii
1 Getting Started
• What is C
• Getting Started with C
The C Character Set
Constants, Variables and Keywords
Types of C Constants
Rules for Constructing Integer Constants
Rules for Constructing Real Constants
Rules for Constructing Character Constants
Types of C Variables
Rules for Constructing Variable Names
C Keywords
• The First C Program
• Compilation and Execution
• Receiving Input
• C Instructions
Type Declaration Instruction
Arithmetic Instruction
Integer and Float Conversions
Hierarchy of Operations
Associativity Of Operators
• Control Instruction in C
• Summary
• Exercise
1
2 Let Us C
efore we can begin to write serious programs in C, it would be interesting to find out what really is C, how it came into existence and how does it compare with other computer languages. In this chapter we would briefly outline these issues. B
Four important aspects of any language are the way it stores data, the way it operates upon this data, how it accomplishes input and output and how it lets you control the sequence of execution of instructions in a program. We would discuss the first three of these building blocks in this chapter.
What is C
C is a programming language developed at AT & T’s Bell Laboratories of USA in 1972. It was designed and written by a man named Dennis Ritchie. In the late seventies C began to replace the more familiar languages of that time like PL/I, ALGOL, etc. No one pushed C. It wasn’t made the ‘official’ Bell Labs language. Thus, without any advertisement C’s reputation spread and its pool of users grew. Ritchie seems to have been rather surprised that so many programmers preferred C to older languages like FORTRAN or PL/I, or the newer ones like Pascal and APL. But, that's what happened.
Possibly why C seems so popular is because it is reliable, simple and easy to use. Moreover, in an industry where newer languages, tools and technologies emerge and vanish day in and day out, a language that has survived for more than 3 decades has to be really good.
An opinion that is often heard today is – “C has been already superceded by languages like C++, C# and Java, so why bother to
Chapter 1: Getting Started 3
learn C today”. I seriously beg to differ with this opinion. There are several reasons for this:
(a)
(b)
(c)
(d)
I believe that nobody can learn C++ or Java directly. This is because while learning these languages you have things like classes, objects, inheritance, polymorphism, templates, exception handling, references, etc. do deal with apart from knowing the actual language elements. Learning these complicated concepts when you are not even comfortable with the basic language elements is like putting the cart before the horse. Hence one should first learn all the language elements very thoroughly using C language before migrating to C++, C# or Java. Though this two step learning process may take more time, but at the end of it you will definitely find it worth the trouble.
C++, C# or Java make use of a principle called Object Oriented Programming (OOP) to organize the program. This organizing principle has lots of advantages to offer. But even while using this organizing principle you would still need a good hold over the language elements of C and the basic programming skills.
Though many C++ and Java based programming tools and frameworks have evolved over the years the importance of C is still unchallenged because knowingly or unknowingly while using these frameworks and tools you would be still required to use the core C language elements—another good reason why one should learn C before C++, C# or Java.
Major parts of popular operating systems like Windows, UNIX, Linux is still written in C. This is because even today when it comes to performance (speed of execution) nothing beats C. Moreover, if one is to extend the operating system to work with new devices one needs to write device driver programs. These programs are exclusively written in C.
4 Let Us C
(e)
(f)
(g)
Mobile devices like cellular phones and palmtops are becoming increasingly popular. Also, common consumer devices like microwave oven, washing machines and digital cameras are getting smarter by the day. This smartness comes from a microprocessor, an operating system and a program embedded in this devices. These programs not only have to run fast but also have to work in limited amount of memory. No wonder that such programs are written in C. With these constraints on time and space, C is the language of choice while building such operating systems and programs.
You must have seen several professional 3D computer games where the user navigates some object, like say a spaceship and fires bullets at the invaders. The essence of all such games is speed. Needless to say, such games won't become popular if they takes a long time to move the spaceship or to fire a bullet. To match the expectations of the player the game has to react fast to the user inputs. This is where C language scores over other languages. Many popular gaming frameworks have been built using C language.
At times one is required to very closely interact with the hardware devices. Since C provides several language elements that make this interaction feasible without compromising the performance it is the preferred choice of the programmer.
I hope that these are very convincing reasons why one should adopt C as the first and the very important step in your quest for learning programming languages.
Getting Started with C
Communicating with a computer involves speaking the language the computer understands, which immediately rules out English as the language of communication with computer. However, there is
Chapter 1: Getting Started 5
a close analogy between learning English language and learning C language. The classical method of learning English is to first learn the alphabets used in the language, then learn to combine these alphabets to form words, which in turn are combined to form sentences and sentences are combined to form paragraphs. Learning C is similar and easier. Instead of straight-away learning how to write programs, we must first know what alphabets, numbers and special symbols are used in C, then how using them constants, variables and keywords are constructed, and finally how are these combined to form an instruction. A group of instructions would be combined later on to form a program. This is illustrated in the Figure 1.1.
Alphabets
Words
Sentences
Paragraphs
Alphabets Digits Special sy- mbols
Constants Variables Keywords
Instructions
Program
Steps in learning English language:
Steps in learning C:
Figure 1.1
The C Character Set
A character denotes any alphabet, digit or special symbol used to represent information. Figure 1.2 shows the valid alphabets, numbers and special symbols allowed in C.
6 Let Us C
Alphabets
A, B, ….., Y, Z
a, b, ……, y, z
Digits
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special symbols
~ ‘ ! @ # % ^ & * ( ) _ - + = | \ { }
[ ] : ; " ' < > , . ? /
Figure 1.2
Constants, Variables and Keywords
The alphabets, numbers and special symbols when properly combined form constants, variables and keywords. Let us see what are ‘constants’ and ‘variables’ in C. A constant is an entity that doesn’t change whereas a variable is an entity that may change.
In any program we typically do lots of calculations. The results of these calculations are stored in computers memory. Like human memory the computer memory also consists of millions of cells. The calculated values are stored in these memory cells. To make the retrieval and usage of these values easy these memory cells (also called memory locations) are given names. Since the value stored in each location may change the names given to these locations are called variable names. Consider the following example.
Here 3 is stored in a memory location and a name x is given to it. Then we are assigning a new value 5 to the same memory location x. This would overwrite the earlier value 3, since a memory location can hold only one value at a time. This is shown in Figure 1.3.
Chapter 1: Getting Started 7
x = 3 x = 5
Figure 1.3
x 3
x 5
Since the location whose name is x can hold different values at different times x is known as a variable. As against this, 3 or 5 do not change, hence are known as constants.
Types of C Constants
C constants can be divided into two major categories:
(a)
(b)
Primary Constants
Secondary Constants
These constants are further categorized as shown in Figure 1.4.
8 Let Us C
Figure 1.4 C Constants
Primary Constants
Secondary Constants
Integer Constant
Real Constant
Character Constant
Array
Pointer
Structure
Union
Enum,etc.
At this stage we would restrict our discussion to only Primary Constants, namely, Integer, Real and Character constants. Let us see the details of each of these constants. For constructing these different types of constants certain rules have been laid down. These rules are as under:
Rules for Constructing Integer Constants
An integer constant must have at least one digit. (a)
(b)
(c)
(d)
(e)
(f)
It must not have a decimal point.
It can be either positive or negative.
If no sign precedes an integer constant it is assumed to be positive.
No commas or blanks are allowed within an integer constant.
The allowable range for integer constants is -32768 to 32767.
Truly speaking the range of an Integer constant depends upon the compiler. For a 16-bit compiler like Turbo C or Turbo C++ the
Chapter 1: Getting Started 9
range is –32768 to 32767. For a 32-bit compiler the range would be even greater. Question like what exactly do you mean by a 16-bit or a 32-bit compiler, what range of an Integer constant has to do with the type of compiler and such questions are discussed in detail in Chapter 16. Till that time it would be assumed that we are working with a 16-bit compiler.
Ex.: 426
+782
-8000
-7605
Rules for Constructing Real Constants
Real constants are often called Floating Point constants. The real constants could be written in two forms—Fractional form and Exponential form.
Following rules must be observed while constructing real constants expressed in fractional form:
(a)
(b)
(c)
(d)
(e)
A real constant must have at least one digit.
It must have a decimal point.
It could be either positive or negative.
Default sign is positive.
No commas or blanks are allowed within a real constant.
Ex.: +325.34
426.0
-32.76
-48.5792
The exponential form of representation of real constants is usually used if the value of the constant is either too small or too large. It however doesn’t restrict us in any way from using exponential form of representation for other real constants.
10 Let Us C
In exponential form of representation, the real constant is represented in two parts. The part appearing before ‘e’ is called mantissa, whereas the part following ‘e’ is called exponent.
Following rules must be observed while constructing real constants expressed in exponential form:
(a)
(b)
(c)
(d)
(e)
(a)
(b)
The mantissa part and the exponential part should be separated by a letter e.
The mantissa part may have a positive or negative sign.
Default sign of mantissa part is positive.
The exponent must have at least one digit, which must be a positive or negative integer. Default sign is positive.
Range of real constants expressed in exponential form is -3.4e38 to 3.4e38.
Ex.: +3.2e-5
4.1e8
-0.2e+3
-3.2e-5
Rules for Constructing Character Constants
A character constant is a single alphabet, a single digit or a single special symbol enclosed within single inverted commas. Both the inverted commas should point to the left. For example, ’A’ is a valid character constant whereas ‘A’ is not.
The maximum length of a character constant can be 1 character.
Ex.: 'A'
'I'
'5'
'='
Chapter 1: Getting Started 11
Types of C Variables
As we saw earlier, an entity that may vary during program execution is called a variable. Variable names are names given to locations in memory. These locations can contain integer, real or character constants. In any language, the types of variables that it can support depend on the types of constants that it can handle. This is because a particular type of variable can hold only the same type of constant. For example, an integer variable can hold only an integer constant, a real variable can hold only a real constant and a character variable can hold only a character constant.
The rules for constructing different types of constants are different. However, for constructing variable names of all types the same set of rules apply. These rules are given below.
Rules for Constructing Variable Names
(a)
(b)
(c)
(d)
A variable name is any combination of 1 to 31 alphabets, digits or underscores. Some compilers allow variable names whose length could be up to 247 characters. Still, it would be safer to stick to the rule of 31 characters. Do not create unnecessarily long variable names as it adds to your typing effort.
The first character in the variable name must be an alphabet or underscore.
No commas or blanks are allowed within a variable name.
No special symbol other than an underscore (as in gross_sal) can be used in a variable name.
Ex.: si_int
m_hra
pop_e_89
These rules remain same for all the types of primary and secondary variables. Naturally, the question follows... how is C able to differentiate between these variables? This is a rather simple
12 Let Us C
matter. C compiler is able to distinguish between the variable names by making it compulsory for you to declare the type of any variable name that you wish to use in a program. This type declaration is done at the beginning of the program. Following are the examples of type declaration statements:
Ex.: int si, m_hra ;
float bassal ;
char code ;
Since, the maximum allowable length of a variable name is 31 characters, an enormous number of variable names can be constructed using the above-mentioned rules. It is a good practice to exploit this enormous choice in naming variables by using meaningful variable names.
Thus, if we want to calculate simple interest, it is always advisable to construct meaningful variable names like prin, roi, noy to represent Principle, Rate of interest and Number of years rather than using the variables a, b, c.
C Keywords
Keywords are the words whose meaning has already been explained to the C compiler (or in a broad sense to the computer). The keywords cannot be used as variable names because if we do so we are trying to assign a new meaning to the keyword, which is not allowed by the computer. Some C compilers allow you to construct variable names that exactly resemble the keywords. However, it would be safer not to mix up the variable names and the keywords. The keywords are also called ‘Reserved words’.
There are only 32 keywords available in C. Figure 1.5 gives a list of these keywords for your ready reference. A detailed discussion of each of these keywords would be taken up in later chapters wherever their use is relevant.
Chapter 1: Getting Started 13
auto
double
int
struct
break
else
long
switch
case
enum
register
typedef
char
extern
return
union
const
float
short
unsigned
continue
for
signed
void
default
goto
sizeof
volatile
do
if
static
while
Figure 1.5
Note that compiler vendors (like Microsoft, Borland, etc.) provide their own keywords apart from the ones mentioned above. These include extended keywords like near, far, asm, etc. Though it has been suggested by the ANSI committee that every such compiler specific keyword should be preceded by two underscores (as in __asm ), not every vendor follows this rule.
The First C Program
Armed with the knowledge about the types of variables, constants & keywords the next logical step is to combine them to form instructions. However, instead of this, we would write our first C program now. Once we have done that we would see in detail the instructions that it made use of.
Before we begin with our first C program do remember the following rules that are applicable to all C programs:
(a)
Each instruction in a C program is written as a separate statement. Therefore a complete C program would comprise of a series of statements.
14 Let Us C
(b)
(c)
(d)
(e)
(f)
The statements in a program must appear in the same order in which we wish them to be executed; unless of course the logic of the problem demands a deliberate ‘jump’ or transfer of control to a statement, which is out of sequence.
Blank spaces may be inserted between two words to improve the readability of the statement. However, no blank spaces are allowed within a variable, constant or keyword.
All statements are entered in small case letters.
C has no specific rules for the position at which a statement is to be written. That’s why it is often called a free-form language.
Every C statement must end with a ;. Thus ; acts as a statement terminator.
Let us now write down our first C program. It would simply calculate simple interest for a set of values representing principle, number of years and rate of interest.
/* Calculation of simple interest */
/* Author gekay Date: 25/05/2004 */
main( )
{
int p, n ;
float r, si ;
p = 1000 ;
n = 3 ;
r = 8.5 ;
/* formula for simple interest */
si = p * n * r / 100 ;
printf ( "%f" , si ) ;
Chapter 1: Getting Started 15
}
Now a few useful tips about the program...
− Comment about the program should be enclosed within /* */. For example, the first two statements in our program are comments.
− Though comments are not necessary, it is a good practice to begin a program with a comment indicating the purpose of the program, its author and the date on which the program was written.
− Any number of comments can be written at any place in the program. For example, a comment can be written before the statement, after the statement or within the statement as shown below:
/* formula */ si = p * n * r / 100 ;
si = p * n * r / 100 ; /* formula */
si = p * n * r / /* formula */ 100 ;
− Sometimes it is not so obvious as to what a particular statement in a program accomplishes. At such times it is worthwhile mentioning the purpose of the statement (or a set of statements) using a comment. For example:
/* formula for simple interest */
si = p * n * r / 100 ;
− Often programmers seem to ignore writing of comments. But when a team is building big software well commented code is almost essential for other team members to understand it.
16 Let Us C
− Although a lot of comments are probably not necessary in this program, it is usually the case that programmers tend to use too few comments rather than too many. An adequate number of comments can save hours of misery and suffering when you later try to figure out what the program does.
− The normal language rules do not apply to text written within /* .. */. Thus we can type this text in small case, capital or a combination. This is because the comments are solely given for the understanding of the programmer or the fellow programmers and are completely ignored by the compiler.
− Comments cannot be nested. For example,
/* Cal of SI /* Author sam date 01/01/2002 */ */
is invalid.
− A comment can be split over more than one line, as in,
/* This is
a jazzy
comment */
Such a comment is often called a multi-line comment.
− main( ) is a collective name given to a set of statements. This name has to be main( ), it cannot be anything else. All statements that belong to main( ) are enclosed within a pair of braces { } as shown below.
main( )
{
statement 1 ;
statement 2 ;
Chapter 1: Getting Started 17
statement 3 ;
}
− Technically speaking main( ) is a function. Every function has a pair of parentheses ( ) associated with it. We would discuss functions and their working in great detail in Chapter 5.
− Any variable used in the program must be declared before using it. For example,
int p, n ;
float r, si ;
− Any C statement always ends with a ;
For example,
float r, si ;
r = 8.5 ;
− In the statement,
si = p * n * r / 100 ;
* and / are the arithmetic operators. The arithmetic operators available in C are +, -, * and /. C is very rich in operators. There are about 45 operators available in C. Surprisingly there is no operator for exponentiation... a slip, which can be forgiven considering the fact that C has been developed by an individual, not by a committee.
− Once the value of si is calculated it needs to be displayed on the screen. Unlike other languages, C does not contain any instruction to display output on the screen. All output to screen is achieved using readymade library functions. One such
18 Let Us C
function is printf( ). We have used it display on the screen the value contained in si.
The general form of printf( ) function is,
printf ( "
- ) ;
%f for printing real values
%d for printing integer values
%c for printing character values
In addition to format specifiers like %f, %d and %c the format string may also contain any other characters. These characters are printed as they are when the printf( ) is executed.
Following are some examples of usage of printf( ) function:
printf ( "%f", si ) ;
printf ( "%d %d %f %f", p, n, r, si ) ;
printf ( "Simple interest = Rs. %f", si ) ;
printf ( "Prin = %d \nRate = %f", p, r ) ;
The output of the last statement would look like this...
Prin = 1000
Rate = 8.5
What is ‘\n’ doing in this statement? It is called newline and it takes the cursor to the next line. Therefore, you get the output split over two lines. ‘\n’ is one of the several Escape Sequences available in C. These are discussed in detail in Chapter 11. Right now, all that we can say is ‘\n’ comes in
Chapter 1: Getting Started 19
handy when we want to format the output properly on separate lines.
printf( ) can not only print values of variables, it can also print the result of an expression. An expression is nothing but a valid combination of constants, variables and operators. Thus, 3, 3 + 2, c and a + b * c – d all are valid expressions. The results of these expressions can be printed as shown below:
printf ( "%d %d %d %d", 3, 3 + 2, c, a + b * c – d ) ;
Note that 3 and c also represent valid expressions.
Compilation and Execution
Once you have written the program you need to type it and instruct the machine to execute it. To type your C program you need another program called Editor. Once the program has been typed it needs to be converted to machine language (0s and 1s) before the machine can execute it. To carry out this conversion we need another program called Compiler. Compiler vendors provide an Integrated Development Environment (IDE) whi
No comments:
Post a Comment