The c programming language 2nd edition download free pdf






















Appendix B is a summary of the facilities of the standard library. It too is meant for reference by programmers, not implementers. Appendix C is a concise summary of the changes from the original version. With a decade more experience, we still feel that way.

We hope that this book will help you learn C and use it well. Do you like this book? It is simple, modern, object oriented, and type-safe. Microsoft Press published the specification for the beta version of C , and then revised that for version 1. The printed books, however, were nothing more than the spec printed out with covers bound on.

This new version should sell much better, because of several factors Tuesday, November 23, Code with C. Books C Books. Kernighan Beginning C pdf — Ivor Horton. Please enter your comment! Please enter your name here. What appears to be a character on the keyboard or screen is of course, like everything else, stored internally just as a bit pattern.

The type char is specifically meant for storing such character data, but any integer type can be used. We used int for a subtle but important reason.

The problem is distinguishing the end of input from valid data. The solution is that getchar returns a distinctive value when there is no more input, a value that cannot be confused with any real character. We must declare c to be a type big enough to hold any value that getchar returns. We can't use char since c must be big enough to hold EOF in addition to any possible char. Therefore we use int. 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. This means that a assignment can appear as part of a larger expression. 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! More on this in Chapter 2. Exercsise Verify that the expression getchar! Write a program to print the value of EOF. There is a corresponding operator -- to decrement by 1. 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. Although on some machines, int and long are the same size, on others an int is 16 bits, with a maximum value of , and it would take relatively little input to overflow an int counter.

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. 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. As we mentioned above, the standard library ensures that an input text stream appears as a sequence of lines, each terminated by a newline. The if statement tests the parenthesized condition, and if the condition is true, executes the statement or group of statements in braces that follows. We have again indented to show what is controlled by what.

As we will see in Chapter 2, the result is usually a legal expression, so you will get no warning. A character written between single quotes represents an integer value equal to the numerical value of the character in the machine's character set. This is called a character constant, although it is just another way to write a small integer.

So, for example, 'A' is a character constant; in the ASCII character set its value is 65, the internal representation of the character A. Of course, 'A' is to be preferred over its meaning is obvious, and it is independent of a particular character set. The topic of strings versus characters is discussed further in Chapter 2.

Write a program to count blanks, tabs, and newlines. Write a program to copy its input to its output, replacing each string of one or more blanks by a single blank. This makes tabs and backspaces visible in an unambiguous way. This is a bare-bones version of the UNIX program wc. We prefer the symbolic constants IN and OUT to the literal values 1 and 0 because they make the program more readable.

In a program as tiny as this, it makes little difference, but in larger programs, the increase in clarity is well worth the modest extra effort to write it this way from the beginning. You'll also find that it's easier to make extensive changes in programs where magic numbers appear only as symbolic constants. This is not a special case, but a consequence of the fact that an assignment is an expression with the value and assignments associated from right to left.

If c is a blank, there is no need to test whether it is a newline or tab, so these tests are not made. This isn't particularly important here, but is significant in more complicated situations, as we will soon see. The example also shows an else, which specifies an alternative action if the condition part of an if statement is false. The general form is if expression statement1 else statement2 One and only one of the two statements associated with an if-else is performed.

If the expression is true, statement1 is executed; if not, statement2 is executed. Each statement can be a single statement or several in braces. In the word count program, the one after the else is an if that controls two statements in braces. How would you test the word count program? What kinds of input are most likely to uncover bugs if there are any?

Write a program that prints its input one word per line. This is artificial, but it permits us to illustrate several aspects of C in one program. There are twelve categories of input, so it is convenient to use an array to hold the number of occurrences of each digit, rather than ten individual variables.

Array subscripts always start at zero in C, so the elements are ndigit[0], ndigit[1], This is reflected in the for loops that initialize and print the array. A subscript can be any integer expression, which includes integer variables like i, and integer constants. This particular program relies on the properties of the character representation of the digits. If it is, the numeric value of that digit is c - '0' This works only if '0', '1', Fortunately, this is true for all character sets.

By definition, chars are just small integers, so char variables and constants are identical to ints in arithmetic expressions. This is natural and convenient; for example c-'0' is an integer expression with a value between 0 and 9 corresponding to the character '0' to '9' stored in c, and thus a valid subscript for the array ndigit.

The conditions are evaluated in order from the top until some condition is satisfied; at that point the corresponding statement part is executed, and the entire construction is finished. Any statement can be several statements enclosed in braces. If none of the conditions is satisfied, the statement after the final else is executed if it is present.

If the final else and statement are omitted, as in the word count program, no action takes place. There can be any number of else if condition statement groups between the initial if and the final else. As a matter of style, it is advisable to format this construction as we have shown; if each if were indented past the previous else, a long sequence of decisions would march off the right side of the page.

The switch statement, to be discussed in Chapter 4, provides another way to write a multi- way branch that is particulary suitable when the condition is whether some integer or character expression matches one of a set of constants.

For contrast, we will present a switch version of this program in Section 3. Write a program to print a histogram of the lengths of words in its input. It is easy to draw the histogram with the bars horizontal; a vertical orientation is more challenging. Write a program to print a histogram of the frequencies of different characters in its input.

A function provides a convenient way to encapsulate some computation, which can then be used without worrying about its implementation. With properly designed functions, it is possible to ignore how a job is done; knowing what is done is sufficient. C makes the sue of functions easy, convinient and efficient; you will often see a short function defined and called only once, just because it clarifies some piece of code.

So far we have used only functions like printf, getchar and putchar that have been provided for us; now it's time to write a few of our own.

That is, the value of power 2,5 is This function is not a practical exponentiation routine, since it handles only positive powers of small integers, but it's good enough for illustration. The standard library contains a function pow x,y that computes xy. Here is the function power and a main program to exercise it, so you can see the whole structure at once.

If the source program appears in several files, you may have to say more to compile and load it than if it all appears in one, but that is an operating system matter, not a language attribute. For the moment, we will assume that both functions are in the same file, so whatever you have learned about running C programs will still work.

In an expression, power 2,i is an integer just as 2 and i are. Not all functions produce an integer value; we will take this up in Chapter 4. The first line of power itself, int power int base, int n declares the parameter types and names, and the type of the result that the function returns. The names used by power for its parameters are local to power, and are not visible to any other function: other routines can use the same names without conflict.

This is also true of the variables i and p: the i in power is unrelated to the i in main. We will generally use parameter for a variable named in the parenthesized list in a function.

The terms formal argument and actual argument are sometimes used for the same distinction. The value that power computes is returned to main by the return: statement. And the calling function can ignore a value returned by a function. You may have noticed that there is a return statement at the end of main. Since main is a function like any other, it may return a value to its caller, which is in effect the environment in which the program was executed. Typically, a return value of zero implies normal termination; non-zero values signal unusual or erroneous termination conditions.

In the interests of simplicity, we have omitted return statements from our main functions up to this point, but we will include them hereafter, as a reminder that programs should return status to their environment. The declaration int power int base, int n ; just before main says that power is a function that expects two int arguments and returns an int. This declaration, which is called a function prototype, has to agree with the definition and uses of power.

It is an error if the definition of a function or any uses of it do not agree with its prototype. Indeed, parameter names are optional in a function prototype, so for the prototype we could have written int power int, int ; Well-chosen names are good documentation however, so we will often use them.

A note of history: the biggest change between ANSI C and earlier versions is how functions are declared and defined. The body of the function is the same as before. The declaration of power at the beginning of the program would have looked like this: int power ; No parameter list was permitted, so the compiler could not readily check that power was being called correctly.

Indeed, since by default power would have been assumed to return an int, the entire declaration might well have been omitted. The new syntax of function prototypes makes it much easier for a compiler to detect errors in the number of arguments or their types.

The old style of declaration and definition still works in ANSI C, at least for a transition period, but we strongly recommend that you use the new form when you have a compiler that supports it. Exercise 1.

Rewrite the temperature conversion program of Section 1. Call by value is an asset, however, not a liability. It usually leads to more compact programs with fewer extraneous variables, because parameters can be treated as conveniently initialized local variables in the called routine. For example, here is a version of power that makes use of this property. Whatever is done to n inside power has no effect on the argument that power was originally called with. When necessary, it is possible to arrange for a function to modify a variable in a calling routine.

We will cover pointers in Chapter 5. The story is different for arrays. When the name of an array is used as an argument, the value passed to the function is the location or address of the beginning of the array - there is no copying of array elements. By subscripting this value, the function can access and alter any argument of the array. This is the topic of the next section. To illustrate the use of character arrays and functions to manipulate them, let's write a program that reads a set of text lines and prints the longest.

The outline is simple enough: while there's another line if it's longer than the previous longest save it save its length print longest line This outline makes it clear that the program divides naturally into pieces. One piece gets a new line, another saves it, and the rest controls the process. Since things divide so nicely, it would be well to write them that way too. Accordingly, let us first write a separate function getline to fetch the next line of input.

We will try to make the function useful in other contexts. At the minimum, getline has to return a signal about possible end of file; a more useful design would be to return the length of the line, or zero if end of file is encountered.

Zero is an acceptable end-of-file return because it is never a valid line length. Every text line has at least one character; even a line containing only a newline has length 1. When we find a line that is longer than the previous longest line, it must be saved somewhere. This suggests a second function, copy, to copy the new line to a safe place.

Finally, we need a main program to control getline and copy. Here is the result. In getline, the arguments are declared by the line int getline char s[], int lim ; which specifies that the first argument, s, is an array, and the second, lim, is an integer. The purpose of supplying the size of an array in a declaration is to set aside storage.

The length of an array s is not necessary in getline since its size is set in main. This line also declares that getline returns an int; since int is the default return type, it could be omitted. Some functions return a useful value; others, like copy, are used only for their effect and return no value.

The return type of copy is void, which states explicitly that no value is returned. It is worth mentioning in passing that even a program as small as this one presents some sticky design problems. For example, what should main do if it encounters a line which is bigger than its limit? By testing the length and the last character returned, main can determine whether the line was too long, and then cope as it wishes.

In the interests of brevity, we have ignored this issue. There is no way for a user of getline to know in advance how long an input line might be, so getline checks for overflow.

On the other hand, the user of copy already knows or can find out how big the strings are, so we have chosen not to add error checking to it. Revise the main routine of the longest-line program so it will correctly print the length of arbitrary long input lines, and as much as possible of the text. Write a program to print all input lines that are longer than 80 characters. Write a program to remove trailing blanks and tabs from each line of input, and to delete entirely blank lines.

Write a function reverse s that reverses the character string s. Use it to write a program that reverses its input a line at a time. Because they are declared within main, no other function can have direct access to them. The same is true of the variables in other functions; for example, the variable i in getline is unrelated to the i in copy.

Each local variable in a function comes into existence only when the function is called, and disappears when the function is exited. This is why such variables are usually known as automatic variables, following terminology in other languages. We will use the term automatic henceforth to refer to these local variables. Chapter 4 discusses the static storage class, in which local variables do retain their values between calls.

Because automatic variables come and go with function invocation, they do not retain their values from one call to the next, and must be explicitly set upon each entry. If they are not set, they will contain garbage. As an alternative to automatic variables, it is possible to define variables that are external to all functions, that is, variables that can be accessed by name by any function. Furthermore, because external variables remain in existence permanently, rather than appearing and disappearing as functions are called and exited, they retain their values even after the functions that set them have returned.

An external variable must be defined, exactly once, outside of any function; this sets aside storage for it. The variable must also be declared in each function that wants to access it; this states the type of the variable.

The declaration may be an explicit extern statement or may be implicit from context. To make the discussion concrete, let us rewrite the longest-line program with line, longest, and max as external variables. This requires changing the calls, declarations, and bodies of all three functions. Syntactically, external definitions are just like definitions of local variables, but since they occur outside of functions, the variables are external.

Before a function can use an external variable, the name of the variable must be made known to the function; the declaration is the same as before except for the added keyword extern. In certain circumstances, the extern declaration can be omitted. If the definition of the external variable occurs in the source file before its use in a particular function, then there is no need for an extern declaration in the function. The extern declarations in main, getline and copy are thus redundant.

In fact, common practice is to place definitions of all external variables at the beginning of the source file, and then omit all extern declarations. If the program is in several source files, and a variable is defined in file1 and used in file2 and file3, then extern declarations are needed in file2 and file3 to connect the occurrences of the variable.

The usual practice is to collect extern declarations of variables and functions in a separate file, historically called a header, that is included by include at the front of each source file.

The suffix. This topic is discussed at length in Chapter 4, and the library itself in Chapter 7 and Appendix B. Since the specialized versions of getline and copy have no arguments, logic would suggest that their prototypes at the beginning of the file should be getline and copy.

But for compatibility with older C programs the standard takes an empty list as an old-style declaration, and turns off all argument list checking; the word void must be used for an explicitly empty list. We will discuss this further in Chapter 4. You should note that we are using the words definition and declaration carefully when we refer to external variables in this section. But external variables are always there even when you don't want them. Relying too heavily on external variables is fraught with peril since it leads to programs whose data connections are not all obvious - variables can be changed in unexpected and even inadvertent ways, and the program is hard to modify.

The second version of the longest-line program is inferior to the first, partly for these reasons, and partly because it destroys the generality of two useful functions by writing into them the names of the variables they manipulate. At this point we have covered what might be called the conventional core of C.

The use of a binary tree together with dynamically allocated memory would allow the arbitrary limit of 30 variables to be avoided.

This would still be a class 1 solution. Should ungets know about buf and bufp , or should it just use ungetch? Should the first character in "s" be sent to ungetch first, or should it be sent last? I assumed that most code calling getch would be of this form: char array[ This requires that the last character be sent first to ungetch first, because getch and ungetch work with a stack.

This allows us to change ungetch and getch in the future, perhaps to use a linked list instead, without affecting ungets. Modify getch and ungetch accordingly. The base must be a value in the range [ The buffer pointed to by digits must be large enough to hold the ASCII string of digits plus a terminating null character. Returns: digits, or NULL if error. Block structure will help. Fix it to push such a character back on the input.

What type does getfloat return as its function value? As a tiny example of this, here's a totally different solution, by Bryan Williams. Write a pointer version of the function strcat that we showed in Chapter 2: strcat s,t copies the string t to the end of s.

Write the function strend s,t , which returns 1 if the string t occurs at the end of the string s, and zero otherwise. For example, strncpy s,t,n copies at most n characters of t to s. Full descriptions are in Appendix B. As far as I can tell, then, this is a Category 0 solution. Rewrite appropriate programs from earlier chapters and exercises with pointers instead of array indexing. Good possibilities include getline Chapters 1 and 4 , atoi , itoa , and their variants Chapters 2, 3, and 4 , reverse Chapter 3 , and strindex and getop Chapter 4.

The base argument specifies the number base for the conversion. How much faster is the program? I can call malloc one million times in under a second - this suggests that the conventional wisdom that malloc is slow and should be avoided may need some more adjustment.

This suggests that the conventional wisdom may be based on real world programs, rather than artificial "how many mallocs per second can I do" benchmarks. Remedy this defect. Write calloc , by calling malloc or by modifying it. The standard library function calloc n, size returns a pointer to n objects of size size, with the storage initialised to zero. Write calloc, by calling malloc or by modifying it. As far as I can tell, this is the only thing which makes this a Category 1, rather than Category 0, solution.

Use the default tab settings if there are no arguments. Here's detab By default, n is 10, say, but it can be changed by an optional argument, so that tail -n prints the last n lines.

The program should behave rationally no matter how unreasonable the input or the value of n. Write the program so it makes the best use of available storage; lines should be stored as in the sorting program of Section 5.

There are two option formats for tail: the new one, in which numbers are arguments to the option letters; and the old one, in which the number precedes any option letters.

Supporting it fully is left as an exercise to the reader ;-. GNU's -f or --follow option is not supported. With that option, the program loops forever on the assumption that the file being tailed is growing. I couldn't figure out how to determine if the program is reading from a pipe in ANSI C; this option is ignored if reading from a pipe. Here, we exploit that property, because we only want to accept options in the form of "-n". That is, how does this program degenerate into just displaying everything it read?

Using modulo arithmetic on an index to a circular array is a common and useful technique. The command line parameter should be in the form of "-n", where n is the number of lines. We don't check for the "-", but just pass it to atoi anyway, and then check if atoi returned us a negative number.

Write a better version. For more information on the language for which this is a lexical analyzer, please see the comment preceding getword below. Hopefully this lies within the rules.



0コメント

  • 1000 / 1000