¡Descarga Teoría del lenguaje C y más Apuntes en PDF de Programación de Ordenadores solo en Docsity!
- Preface....................................................................................................................................
- Preface to the first edition........................................................................................................
- Chapter 1 - A Tutorial Introduction.........................................................................................
- 1.1 Getting Started..............................................................................................................
- 1.2 Variables and Arithmetic Expressions..........................................................................
- 1.3 The for statement.........................................................................................................
- 1.4 Symbolic Constants......................................................................................................
- 1.5 Character Input and Output.........................................................................................
- 1.5.1 File Copying..........................................................................................................
- 1.5.2 Character Counting...............................................................................................
- 1.5.3 Line Counting.......................................................................................................
- 1.5.4 Word Counting.....................................................................................................
- 1.6 Arrays..........................................................................................................................
- 1.7 Functions.....................................................................................................................
- 1.8 Arguments - Call by Value...........................................................................................
- 1.9 Character Arrays..........................................................................................................
- 1.10 External Variables and Scope.....................................................................................
- Chapter 2 - Types, Operators and Expressions.......................................................................
- 2.1 Variable Names............................................................................................................
- 2.2 Data Types and Sizes...................................................................................................
- 2.3 Constants.....................................................................................................................
- 2.4 Declarations.................................................................................................................
- 2.5 Arithmetic Operators...................................................................................................
- 2.6 Relational and Logical Operators.................................................................................
- 2.7 Type Conversions........................................................................................................
- 2.8 Increment and Decrement Operators............................................................................
- 2.9 Bitwise Operators........................................................................................................
- 2.10 Assignment Operators and Expressions......................................................................
- 2.11 Conditional Expressions.............................................................................................
- 2.12 Precedence and Order of Evaluation..........................................................................
- Chapter 3 - Control Flow.......................................................................................................
- 3.1 Statements and Blocks.................................................................................................
- 3.2 If-Else..........................................................................................................................
- 3.3 Else-If..........................................................................................................................
- 3.4 Switch..........................................................................................................................
- 3.5 Loops - While and For.................................................................................................
- 3.6 Loops - Do-While........................................................................................................
- 3.7 Break and Continue.....................................................................................................
- 3.8 Goto and labels............................................................................................................
- Chapter 4 - Functions and Program Structure........................................................................
- 4.1 Basics of Functions......................................................................................................
- 4.2 Functions Returning Non-integers................................................................................
- 4.3 External Variables........................................................................................................
- 4.4 Scope Rules.................................................................................................................
- 4.5 Header Files.................................................................................................................
- 4.6 Static Variables............................................................................................................
- 4.7 Register Variables........................................................................................................
- 4.8 Block Structure............................................................................................................
- 4.9 Initialization.................................................................................................................
- 4.10 Recursion...................................................................................................................
- 4.11 The C Preprocessor....................................................................................................
- 4.11.1 File Inclusion.......................................................................................................
- 4.11.2 Macro Substitution..............................................................................................
- 4.11.3 Conditional Inclusion..........................................................................................
- Chapter 5 - Pointers and Arrays.............................................................................................
- 5.1 Pointers and Addresses................................................................................................
- 5.2 Pointers and Function Arguments.................................................................................
- 5.3 Pointers and Arrays......................................................................................................
- 5.4 Address Arithmetic......................................................................................................
- 5.5 Character Pointers and Functions.................................................................................
- 5.6 Pointer Arrays; Pointers to Pointers.............................................................................
- 5.7 Multi-dimensional Arrays.............................................................................................
- 5.8 Initialization of Pointer Arrays.....................................................................................
- 5.9 Pointers vs. Multi-dimensional Arrays..........................................................................
- 5.10 Command-line Arguments..........................................................................................
- 5.11 Pointers to Functions.................................................................................................
- 5.12 Complicated Declarations.........................................................................................
- Chapter 6 - Structures..........................................................................................................
- 6.1 Basics of Structures...................................................................................................
- 6.2 Structures and Functions............................................................................................
- 6.3 Arrays of Structures...................................................................................................
- 6.4 Pointers to Structures.................................................................................................
- 6.5 Self-referential Structures...........................................................................................
- 6.6 Table Lookup............................................................................................................
- 6.7 Typedef......................................................................................................................
- 6.8 Unions.......................................................................................................................
- 6.9 Bit-fields....................................................................................................................
- Chapter 7 - Input and Output...............................................................................................
- 7.1 Standard Input and Output.........................................................................................
- 7.2 Formatted Output - printf...........................................................................................
- 7.3 Variable-length Argument Lists..................................................................................
- 7.4 Formatted Input - Scanf.............................................................................................
- 7.5 File Access.................................................................................................................
- 7.6 Error Handling - Stderr and Exit................................................................................
- 7.7 Line Input and Output................................................................................................
- 7.8 Miscellaneous Functions............................................................................................
- 7.8.1 String Operations................................................................................................
- 7.8.2 Character Class Testing and Conversion..............................................................
- 7.8.3 Ungetc................................................................................................................
- 7.8.4 Command Execution...........................................................................................
- 7.8.5 Storage Management..........................................................................................
- 7.8.6 Mathematical Functions.......................................................................................
- 7.8.7 Random Number generation................................................................................
- Chapter 8 - The UNIX System Interface..............................................................................
- 8.1 File Descriptors..........................................................................................................
- 8.2 Low Level I/O - Read and Write................................................................................
- 8.3 Open, Creat, Close, Unlink........................................................................................
- 8.4 Random Access - Lseek.............................................................................................
- 8.5 Example - An implementation of Fopen and Getc.......................................................
- 8.6 Example - Listing Directories.....................................................................................
- 8.7 Example - A Storage Allocator..................................................................................
- Appendix A - Reference Manual..........................................................................................
- A.1 Introduction..............................................................................................................
- A.2 Lexical Conventions..................................................................................................
- A.2.1 Tokens...............................................................................................................
- A.2.2 Comments..........................................................................................................
- A.2.3 Identifiers...........................................................................................................
- A.2.4 Keywords...........................................................................................................
- A.2.5 Constants...........................................................................................................
- A.2.6 String Literals.....................................................................................................
- A.3 Syntax Notation........................................................................................................
- A.4 Meaning of Identifiers...............................................................................................
- A.4.1 Storage Class.....................................................................................................
- A.4.2 Basic Types........................................................................................................
- A.4.3 Derived types.....................................................................................................
- A.4.4 Type Qualifiers...................................................................................................
- A.5 Objects and Lvalues..................................................................................................
- A.6 Conversions..............................................................................................................
- A.6.1 Integral Promotion.............................................................................................
- A.6.2 Integral Conversions...........................................................................................
- A.6.3 Integer and Floating...........................................................................................
- A.6.4 Floating Types....................................................................................................
- A.6.5 Arithmetic Conversions......................................................................................
- A.6.6 Pointers and Integers..........................................................................................
- A.6.7 Void...................................................................................................................
- A.6.8 Pointers to Void.................................................................................................
- A.7 Expressions...............................................................................................................
- A.7.1 Pointer Conversion.............................................................................................
- A.7.2 Primary Expressions...........................................................................................
- A.7.3 Postfix Expressions............................................................................................
- A.7.4 Unary Operators.................................................................................................
- A.7.5 Casts..................................................................................................................
- A.7.6 Multiplicative Operators.....................................................................................
- A.7.7 Additive Operators.............................................................................................
- A.7.8 Shift Operators...................................................................................................
- A.7.9 Relational Operators...........................................................................................
- A.7.10 Equality Operators...........................................................................................
- A.7.11 Bitwise AND Operator.....................................................................................
- A.7.12 Bitwise Exclusive OR Operator........................................................................
- A.7.13 Bitwise Inclusive OR Operator.........................................................................
- A.7.14 Logical AND Operator.....................................................................................
- A.7.15 Logical OR Operator........................................................................................
- A.7.16 Conditional Operator........................................................................................
- A.7.17 Assignment Expressions...................................................................................
- A.7.18 Comma Operator..............................................................................................
- A.7.19 Constant Expressions.......................................................................................
- A.8 Declarations..............................................................................................................
- A.8.1 Storage Class Specifiers.....................................................................................
- A.8.2 Type Specifiers...................................................................................................
- A.8.3 Structure and Union Declarations.......................................................................
- A.8.4 Enumerations.....................................................................................................
- A.8.5 Declarators.........................................................................................................
- A.8.6 Meaning of Declarators......................................................................................
- A.8.7 Initialization.......................................................................................................
- A.8.8 Type names........................................................................................................
- A.8.9 Typedef..............................................................................................................
- A.8.10 Type Equivalence.............................................................................................
- A.9 Statements................................................................................................................
- A.9.1 Labeled Statements.............................................................................................
- A.9.2 Expression Statement.........................................................................................
- A.9.3 Compound Statement.........................................................................................
- A.9.4 Selection Statements..........................................................................................
- A.9.5 Iteration Statements...........................................................................................
- A.9.6 Jump statements.................................................................................................
- A.10 External Declarations..............................................................................................
- A.10.1 Function Definitions.........................................................................................
- A.10.2 External Declarations.......................................................................................
- A.11 Scope and Linkage..................................................................................................
- A.11.1 Lexical Scope...................................................................................................
- A.11.2 Linkage............................................................................................................
- A.12 Preprocessing..........................................................................................................
- A.12.1 Trigraph Sequences..........................................................................................
- A.12.2 Line Splicing....................................................................................................
- A.12.3 Macro Definition and Expansion.......................................................................
- A.12.4 File Inclusion....................................................................................................
- A.12.5 Conditional Compilation...................................................................................
- A.12.6 Line Control.....................................................................................................
- A.12.7 Error Generation..............................................................................................
- A.12.8 Pragmas............................................................................................................
- A.12.9 Null directive....................................................................................................
- A.12.10 Predefined names............................................................................................
- A.13 Grammar.................................................................................................................
- Appendix B - Standard Library............................................................................................
- B.1 Input and Output: <stdio.h>......................................................................................
- B.1.1 File Operations...................................................................................................
- B.1.2 Formatted Output...............................................................................................
- B.1.3 Formatted Input..................................................................................................
- B.1.4 Character Input and Output Functions................................................................
- B.1.5 Direct Input and Output Functions......................................................................
- B.1.6 File Positioning Functions...................................................................................
- B.1.7 Error Functions..................................................................................................
- B.2 Character Class Tests: <ctype.h>...............................................................................
- B.3 String Functions: <string.h>......................................................................................
- B.4 Mathematical Functions: <math.h>............................................................................
- B.5 Utility Functions: <stdlib.h>......................................................................................
- B.6 Diagnostics: <assert.h>..............................................................................................
- B.7 Variable Argument Lists: <stdarg.h>.........................................................................
- B.8 Non-local Jumps: <setjmp.h>....................................................................................
- B.9 Signals: <signal.h>....................................................................................................
- B.10 Date and Time Functions: <time.h>.........................................................................
- B.11 Implementation-defined Limits: <limits.h> and <float.h>.........................................
- Appendix C - Summary of Changes.....................................................................................
London, Jim Reeds, Clovis Tondo, and Peter Weinberger. Dave Prosser answered many detailed questions about the ANSI standard. We used Bjarne Stroustrup's C++ translator extensively for local testing of our programs, and Dave Kristol provided us with an ANSI C compiler for final testing. Rich Drechsler helped greatly with typesetting.
Our sincere thanks to all.
Brian W. Kernighan Dennis M. Ritchie
Preface to the first edition
C is a general-purpose programming language with features economy of expression, modern flow control and data structures, and a rich set of operators. C is not a very high level'' language, nor abig'' one, and is not specialized to any particular area of application. But its absence of restrictions and its generality make it more convenient and effective for many tasks than supposedly more powerful languages.
C was originally designed for and implemented on the UNIX operating system on the DEC PDP-11, by Dennis Ritchie. The operating system, the C compiler, and essentially all UNIX applications programs (including all of the software used to prepare this book) are written in C. Production compilers also exist for several other machines, including the IBM System/370, the Honeywell 6000, and the Interdata 8/32. C is not tied to any particular hardware or system, however, and it is easy to write programs that will run without change on any machine that supports C.
This book is meant to help the reader learn how to program in C. It contains a tutorial introduction to get new users started as soon as possible, separate chapters on each major feature, and a reference manual. Most of the treatment is based on reading, writing and revising examples, rather than on mere statements of rules. For the most part, the examples are complete, real programs rather than isolated fragments. All examples have been tested directly from the text, which is in machine-readable form. Besides showing how to make effective use of the language, we have also tried where possible to illustrate useful algorithms and principles of good style and sound design.
The book is not an introductory programming manual; it assumes some familiarity with basic programming concepts like variables, assignment statements, loops, and functions. Nonetheless, a novice programmer should be able to read along and pick up the language, although access to more knowledgeable colleague will help.
In our experience, C has proven to be a pleasant, expressive and versatile language for a wide variety of programs. It is easy to learn, and it wears well as on's experience with it grows. We hope that this book will help you to use it well.
The thoughtful criticisms and suggestions of many friends and colleagues have added greatly to this book and to our pleasure in writing it. In particular, Mike Bianchi, Jim Blue, Stu Feldman, Doug McIlroy Bill Roome, Bob Rosin and Larry Rosler all read multiple volumes with care. We are also indebted to Al Aho, Steve Bourne, Dan Dvorak, Chuck Haley, Debbie Haley, Marion Harris, Rick Holt, Steve Johnson, John Mashey, Bob Mitze, Ralph Muha, Peter Nelson, Elliot Pinson, Bill Plauger, Jerry Spivack, Ken Thompson, and Peter Weinberger for helpful comments at various stages, and to Mile Lesk and Joe Ossanna for invaluable assistance with typesetting.
Brian W. Kernighan Dennis M. Ritchie
hello, world On other systems, the rules will be different; check with a local expert.
Now, for some explanations about the program itself. A C program, whatever its size, consists of functions and variables. A function contains statements that specify the computing operations to be done, and variables store values used during the computation. C functions are like the subroutines and functions in Fortran or the procedures and functions of Pascal. Our example is a function named main. Normally you are at liberty to give functions whatever names you like, but ``main'' is special - your program begins executing at the beginning of main. This means that every program must have a main somewhere.
main will usually call other functions to help perform its job, some that you wrote, and others from libraries that are provided for you. The first line of the program,
#include <stdio.h> tells the compiler to include information about the standard input/output library; the line appears at the beginning of many C source files. The standard library is described in Chapter 7 and Appendix B.
One method of communicating data between functions is for the calling function to provide a list of values, called arguments , to the function it calls. The parentheses after the function name surround the argument list. In this example, main is defined to be a function that expects no arguments, which is indicated by the empty list ( ).
#include <stdio.h> include information about standard library main() define a function called main that received no argument values { statements of main are enclosed in braces printf("hello, world\n"); main calls library function printf to print this sequence of characters } \n represents the newline character
The first C program
The statements of a function are enclosed in braces { }. The function main contains only one statement,
printf("hello, world\n"); A function is called by naming it, followed by a parenthesized list of arguments, so this calls the function printf with the argument "hello, world\n". printf is a library function that prints output, in this case the string of characters between the quotes.
A sequence of characters in double quotes, like "hello, world\n", is called a character string or string constant. For the moment our only use of character strings will be as arguments for printf and other functions.
The sequence \n in the string is C notation for the newline character , which when printed advances the output to the left margin on the next line. If you leave out the \n (a worthwhile experiment), you will find that there is no line advance after the output is printed. You must use \n to include a newline character in the printf argument; if you try something like
printf("hello, world ");
the C compiler will produce an error message.
printf never supplies a newline character automatically, so several calls may be used to build up an output line in stages. Our first program could just as well have been written
#include <stdio.h>
main() { printf("hello, "); printf("world"); printf("\n"); } to produce identical output.
Notice that \n represents only a single character. An escape sequence like \n provides a general and extensible mechanism for representing hard-to-type or invisible characters. Among the others that C provides are \t for tab, \b for backspace, " for the double quote and \ for the backslash itself. There is a complete list in Section 2.3.
Exercise 1-1. Run the ``hello, world'' program on your system. Experiment with leaving out parts of the program, to see what error messages you get.
Exercise 1-2. Experiment to find out what happens when prints's argument string contains \c , where c is some character not listed above.
1.2 Variables and Arithmetic Expressions
The next program uses the formula oC=(5/9)(oF-32) to print the following table of Fahrenheit temperatures and their centigrade or Celsius equivalents:
char character - a single byte short short integer long long integer double double-precision floating point
The size of these objects is also machine-dependent. There are also arrays , structures and unions of these basic types, pointers to them, and functions that return them, all of which we will meet in due course.
Computation in the temperature conversion program begins with the assignment statements
lower = 0; upper = 300; step = 20; which set the variables to their initial values. Individual statements are terminated by semicolons.
Each line of the table is computed the same way, so we use a loop that repeats once per output line; this is the purpose of the while loop
while (fahr <= upper) { ... } The while loop operates as follows: The condition in parentheses is tested. If it is true (fahr is less than or equal to upper), the body of the loop (the three statements enclosed in braces) is executed. Then the condition is re-tested, and if true, the body is executed again. When the test becomes false (fahr exceeds upper) the loop ends, and execution continues at the statement that follows the loop. There are no further statements in this program, so it terminates.
The body of a while can be one or more statements enclosed in braces, as in the temperature converter, or a single statement without braces, as in
while (i < j) i = 2 * i; In either case, we will always indent the statements controlled by the while by one tab stop (which we have shown as four spaces) so you can see at a glance which statements are inside the loop. The indentation emphasizes the logical structure of the program. Although C compilers do not care about how a program looks, proper indentation and spacing are critical in making programs easy for people to read. We recommend writing only one statement per line, and using blanks around operators to clarify grouping. The position of braces is less important, although people hold passionate beliefs. We have chosen one of several popular styles. Pick a style that suits you, then use it consistently.
Most of the work gets done in the body of the loop. The Celsius temperature is computed and assigned to the variable celsius by the statement
celsius = 5 * (fahr-32) / 9; The reason for multiplying by 5 and dividing by 9 instead of just multiplying by 5/9 is that in C, as in many other languages, integer division truncates : any fractional part is discarded. Since 5 and 9 are integers. 5/9 would be truncated to zero and so all the Celsius temperatures would be reported as zero.
This example also shows a bit more of how printf works. printf is a general-purpose output formatting function, which we will describe in detail in Chapter 7. Its first argument is a string of characters to be printed, with each % indicating where one of the other (second, third,
...) arguments is to be substituted, and in what form it is to be printed. For instance, %d specifies an integer argument, so the statement
printf("%d\t%d\n", fahr, celsius); causes the values of the two integers fahr and celsius to be printed, with a tab (\t) between them.
Each % construction in the first argument of printf is paired with the corresponding second argument, third argument, etc.; they must match up properly by number and type, or you will get wrong answers.
By the way, printf is not part of the C language; there is no input or output defined in C itself. printf is just a useful function from the standard library of functions that are normally accessible to C programs. The behaviour of printf is defined in the ANSI standard, however, so its properties should be the same with any compiler and library that conforms to the standard.
In order to concentrate on C itself, we don't talk much about input and output until chapter 7. In particular, we will defer formatted input until then. If you have to input numbers, read the discussion of the function scanf in Section 7.4. scanf is like printf, except that it reads input instead of writing output.
There are a couple of problems with the temperature conversion program. The simpler one is that the output isn't very pretty because the numbers are not right-justified. That's easy to fix; if we augment each %d in the printf statement with a width, the numbers printed will be right- justified in their fields. For instance, we might say
printf("%3d %6d\n", fahr, celsius); to print the first number of each line in a field three digits wide, and the second in a field six digits wide, like this:
0 - 20 - 40 4 60 15 80 26 100 37 ... The more serious problem is that because we have used integer arithmetic, the Celsius temperatures are not very accurate; for instance, 0oF is actually about -17.8oC, not -17. To get more accurate answers, we should use floating-point arithmetic instead of integer. This requires some changes in the program. Here is the second version:
#include <stdio.h> /* print Fahrenheit-Celsius table for fahr = 0, 20, ..., 300; floating-point version */ main() { float fahr, celsius; float lower, upper, step;
lower = 0; /* lower limit of temperatuire scale / upper = 300; / upper limit / step = 20; / step size */ fahr = lower; while (fahr <= upper) { celsius = (5.0/9.0) * (fahr-32.0); printf("%3.0f %6.1f\n", fahr, celsius);
/* print Fahrenheit-Celsius table / main() { int fahr; for (fahr = 0; fahr <= 300; fahr = fahr + 20) printf("%3d %6.1f\n", fahr, (5.0/9.0)(fahr-32)); } This produces the same answers, but it certainly looks different. One major change is the elimination of most of the variables; only fahr remains, and we have made it an int. The lower and upper limits and the step size appear only as constants in the for statement, itself a new construction, and the expression that computes the Celsius temperature now appears as the third argument of printf instead of a separate assignment statement.
This last change is an instance of a general rule - in any context where it is permissible to use the value of some type, you can use a more complicated expression of that type. Since the third argument of printf must be a floating-point value to match the %6.1f, any floating-point expression can occur here.
The for statement is a loop, a generalization of the while. If you compare it to the earlier while, its operation should be clear. Within the parentheses, there are three parts, separated by semicolons. The first part, the initialization
fahr = 0
is done once, before the loop proper is entered. The second part is the test or condition that controls the loop:
fahr <= 300 This condition is evaluated; if it is true, the body of the loop (here a single ptintf) is executed. Then the increment step
fahr = fahr + 20 is executed, and the condition re-evaluated. The loop terminates if the condition has become false. As with the while, the body of the loop can be a single statement or a group of statements enclosed in braces. The initialization, condition and increment can be any expressions.
The choice between while and for is arbitrary, based on which seems clearer. The for is usually appropriate for loops in which the initialization and increment are single statements and logically related, since it is more compact than while and it keeps the loop control statements together in one place.
Exercise 1-5. Modify the temperature conversion program to print the table in reverse order, that is, from 300 degrees to 0.
1.4 Symbolic Constants
A final observation before we leave temperature conversion forever. It's bad practice to bury ``magic numbers'' like 300 and 20 in a program; they convey little information to someone who might have to read the program later, and they are hard to change in a systematic way. One way to deal with magic numbers is to give them meaningful names. A #define line defines a symbolic name or symbolic constant to be a particular string of characters:
#define name replacement list
Thereafter, any occurrence of name (not in quotes and not part of another name) will be replaced by the corresponding replacement text. The name has the same form as a variable name: a sequence of letters and digits that begins with a letter. The replacement text can be any sequence of characters; it is not limited to numbers.
#include <stdio.h> #define LOWER 0 /* lower limit of table / #define UPPER 300 / upper limit / #define STEP 20 / step size */
/* print Fahrenheit-Celsius table */ main() { int fahr;
for (fahr = LOWER; fahr <= UPPER; fahr = fahr + STEP) printf("%3d %6.1f\n", fahr, (5.0/9.0)*(fahr-32)); } The quantities LOWER, UPPER and STEP are symbolic constants, not variables, so they do not appear in declarations. Symbolic constant names are conventionally written in upper case so they can ber readily distinguished from lower case variable names. Notice that there is no semicolon at the end of a #define line.
1.5 Character Input and Output
We are going to consider a family of related programs for processing character data. You will find that many programs are just expanded versions of the prototypes that we discuss here.
EOF is an integer defined in <stdio.h>, but the specific numeric value doesn't matter as long as it is not the same as any char value. By using the symbolic constant, we are assured that nothing in the program depends on the specific numeric value.
The program for copying would be written more concisely by experienced C programmers. In C, any assignment, such as
c = getchar(); is an expression and has a value, which is the value of the left hand side after the assignment. This means that a assignment can appear as part of a larger expression. If the assignment of a character to c is put inside the test part of a while loop, the copy program can be written this way:
#include <stdio.h> /* copy input to output; 2nd version */ main() { int c; while ((c = getchar()) != EOF) putchar(c); } The while gets a character, assigns it to c, and then tests whether the character was the end- of-file signal. If it was not, the body of the while is executed, printing the character. The while then repeats. When the end of the input is finally reached, the while terminates and so does main.
This version centralizes the input - there is now only one reference to getchar - and shrinks the program. The resulting program is more compact, and, once the idiom is mastered, easier to read. You'll see this style often. (It's possible to get carried away and create impenetrable code, however, a tendency that we will try to curb.)
The parentheses around the assignment, within the condition are necessary. The precedence of != is higher than that of =, which means that in the absence of parentheses the relational test != would be done before the assignment =. So the statement
c = getchar() != EOF is equivalent to
c = (getchar() != EOF) This has the undesired effect of setting c to 0 or 1, depending on whether or not the call of getchar returned end of file. (More on this in Chapter 2.)
Exercsise 1-6. Verify that the expression getchar() != EOF is 0 or 1.
Exercise 1-7. Write a program to print the value of EOF.
1.5.2 Character Counting
The next program counts characters; it is similar to the copy program.
#include <stdio.h>
/* count characters in input; 1st version */ main() { long nc;
nc = 0; while (getchar() != EOF)
++nc; printf("%ld\n", nc); } The statement
++nc; presents a new operator, ++, which means increment by one. You could instead write nc = nc
- 1 but ++nc is more concise and often more efficient. There is a corresponding operator -- to decrement by 1. The operators ++ and -- can be either prefix operators (++nc) or postfix operators (nc++); these two forms have different values in expressions, as will be shown in Chapter 2, but ++nc and nc++ both increment nc. For the moment we will will stick to the prefix form.
The character counting program accumulates its count in a long variable instead of an int. long integers are at least 32 bits. Although on some machines, int and long are the same size, on others an int is 16 bits, with a maximum value of 32767, and it would take relatively little input to overflow an int counter. The conversion specification %ld tells printf that the corresponding argument is a long integer.
It may be possible to cope with even bigger numbers by using a double (double precision float). We will also use a for statement instead of a while, to illustrate another way to write the loop.
#include <stdio.h> /* count characters in input; 2nd version */ main() { double nc; for (nc = 0; gechar() != EOF; ++nc) ; printf("%.0f\n", nc); } printf uses %f for both float and double; %.0f suppresses the printing of the decimal point and the fraction part, which is zero.
The body of this for loop is empty, because all the work is done in the test and increment parts. But the grammatical rules of C require that a for statement have a body. The isolated semicolon, called a null statement , is there to satisfy that requirement. We put it on a separate line to make it visible.
Before we leave the character counting program, observe that if the input contains no characters, the while or for test fails on the very first call to getchar, and the program produces zero, the right answer. This is important. One of the nice things about while and for is that they test at the top of the loop, before proceeding with the body. If there is nothing to do, nothing is done, even if that means never going through the loop body. Programs should act intelligently when given zero-length input. The while and for statements help ensure that programs do reasonable things with boundary conditions.
1.5.3 Line Counting
The next program counts input lines. As we mentioned above, the standard library ensures that an input text stream appears as a sequence of lines, each terminated by a newline. Hence, counting lines is just counting newlines:
#include <stdio.h>
/* count lines in input */ main()