The C Programming

The C Programming

Lượt xem: 51,441Lượt tải: 10Số trang: 217

Mô tả tài liệu

The computing world has undergone a revolution since the publication of The C Programming Language in 1978.

Tóm tắt nội dung

1.2 Variables and Character Input and Character 2 - Types, Operators and Operators and 4 - Functions and Program Functions Returning Pointers and Function Character Pointers and Pointers to and Function Character Input and Output Direct Input and Output File Error String computing world has undergone a since the of The C an extensive set of functions for input and output, memory Second Edition of The C Language describes C as defined by the ANSI the most visible change is the new form of function and are central to C for local testing of our programs, and Dave Kristol provided us with an ANSI C C is a language with features economy of modern C was designed for and on the UNIX operating system on the DEC The operating system, the C compiler, and all and it is easy to write programs that will run without change on any machine that This book is meant to help the reader learn how to program in concepts like loops, and our C has proven to be a pleasant, and versatile language for a useful programs, and to do that we have to on the basics: variables control flow, and the rudiments of input and leaving out of this chapter features of C that are important for writing include pointers, most of C's rich set of several examples do not use the full power of C, they are not as concise and elegant as they might The only way to learn a new language is by writing programs in to write is the same for all C, the program to print ``hello, world'' is the UNIX operating system you must create the program in a file whose name ends in ``.c'', A C program, whatever its size, functions and function contains that specify the to be done, and variables store values used during the functions is a function named you like, but ``main'' is special - your program begins executing at the beginning of The first line of the program, tells the compiler to include about the standard library; the line list of values, called to the function it calls. In this example, main is defined to be a function that expects no main() define a function called main calls library function printf to print this sequence of \n the newline first C program The of a function are enclosed in braces { }. A function is called by naming it, followed by a list of so this calls the function printf with the argument "hello, is a library function output, in this case the string of between the quotes. A sequence of in double quotes, like "hello, world\n", is called a the moment our only use of character strings will be for printf and other sequence \n in the string is C notation for the newline which when \n to include a newline character in the printf argument; if you try something like Notice that \n only a single others that C provides are \t for tab, \b for \" for the double quote and \\ for \c, where c is some character not listed Variables and program itself still consists of the of a single function named including comments, loops , and Any C, all variables must be declared before they are used, usually at the beginning of before any type int means that the variables listed are integers; by contrast with float, which means C provides several other data types besides int and float, unions of these basic types, pointers to them, and functions that return them, all of which in the program begins with the which set the variables to their initial line of the table is computed the same way, so we use a loop that repeats once per while loop operates as follows: The condition in is are no further in this program, so it to the variable celsius by the statement output function, which we will describe in detail in Chapter 7. string of to be printed, with each % where one of the other (second, an integer argument, so the statement causes the values of the two integers fahr and celsius to be printed, with a tab (\t) the way, printf is not part of the C language; there is no input or output defined in C printf is just a useful function from the standard library of functions that are to C order to on C itself, we don't talk much about input and output until chapter 7. we augment each %d in the printf statement with a width, the numbers printed will be accurate answers, we should use instead of operator has one operand and one integer operand, however, will be converted to floating point before the operation is constants with explicit decimal points even when they have integral detailed rules for when integers are converted to floating point are in Chapter 2. also work in the natural way - the int is converted to float before the operation is done. The printf %3.0f says that a number (here fahr) is to be printed at least three wide, with no decimal point and no fraction another number (celsius) that is to be printed at least six wide, with 1 %6d print as decimal integer, at least 6 wide %6f print as floating point, at least 6 wide %.2f print as floating point, 2 after decimal others, printf also %o for octal, %x for %c for %s for character string and %% for a program to print the Celsius to are plenty of different ways to write a program for a task. the third argument of printf instead of a separate value of some type, you can use a more of that of printf must be a value to match the %6.1f, any the program to print the table in reverse name or symbolic constant to be a string of any sequence of it is not limited to Character Input and Output We are going to consider a family of related programs for character each input or output stream confirm this model; the C using the library need The standard library provides several functions for reading or writing one character at a character from a text stream and returns that as its variable c contains the next character of function putchar prints a character each time it is called: prints the contents of the integer variable c as a usually on the input to its output one character at a time: int data, but any integer type can be used. We must declare c to be a type We can't use char since c must be big EOF is an integer defined in but the specific numeric value doesn't matter as long in the program depends on the specific numeric program for copying would be written more concisely by C any such as is an and has a value, which is the value of the left hand side after the to c is put inside the test part of a while loop, the copy program can be written this int c; The while gets a assigns it to c, and then tests whether the character was the end- the a program to print the value of EOF. The next program counts it is similar to the copy count in input; 1st version (nc++); these two forms have different values in as will be shown in The character counting program its count in a long variable instead of an int. on others an int is 16 bits, with a maximum value of 32767, and it would take little We will also use a for statement instead of a while, to another way to write /* count in input; 2nd version */ printf uses %f for both float and double; %.0f the printing of the decimal point But the rules of C require that a for statement have a we leave the character counting program, observe that if the input contains the while or for test fails on the very first call to getchar, and the next program counts input c, nl; if (c == '\n') The double equals sign == is the C notation for ``is equal to'' (like Pascal's single = or symbol is used to the equality test from the single = that C uses for A character written between single quotes an integer value equal to the of the character in the machine's character set. This is called a character for example, 'A' is a in the ASCII character set its value is 65, the internal of the escape sequences used in string constants are also legal in character so for the value of the newline which is 10 in '\n' is a single and in is just an integer; on the other hand, '\n' is a string constant that happens to contain only one is discussed further in Chapter 2. Write a program to count blanks, tabs, and a program to copy its input to its output, replacing each string of one or Write a program to copy its input to its output, replacing each tab by \t, each The fourth in our series of useful programs counts lines, words, and with the that a word is any sequence of that does not contain a blank, tab or /* count lines, words, and in input */ int c, nl, nw, nc, state; if (c == '\n') if (c == ' ' || c == '\n' || c = time the program the first character of a word, it counts one more state records whether the program is currently in a word or not; initially it is ``not values 1 and 0 because they make the program more extensive changes in programs where magic numbers appear only as symbolic is an with the value and from right to left. The operator || means OR, so the line if (c == ' ' || c == '\n' || c = of the tab There is a operator && for AND; its Write a program that prints its input one word per line. Let is write a program to count the number of of each digit, of white space to several aspects of C in one int c, i, nwhite, if (c == ' ' || c == '\n' || c == '\t') A subscript can be any integer which includes integer variables like i, and program relies on the of the character of the whether the character in c is a digit. c - '0' By chars are just small integers, so char variables and constants are identical to ints in is natural and for example c-'0' is an with a value between 0 and 9 to the character '0' to '9' stored in c, else if (c == ' ' || c == '\n' || c == in programs as a way to express a multi-way switch to be discussed in Chapter 4, provides another way to write a branch that is suitable when the condition is whether some integer or a program to print a histogram of the lengths of words in its a program to print a histogram of the of different C, a function is to a or function in Fortran, or a procedure or far we have used only functions like printf, getchar and putchar that have like the ** of Fortran, let us the mechanics of function by writing a function to raise an integer m to a positive integer power n. Here is the function power and a main program to exercise it, so you can see the whole /* test power function */ for (i = 1; i <= n; ++i) A function has this form: if can appear in any order, and in one source file or several, although no same file, so whatever you have learned about running C programs will still work. The function power is called twice by main, in the line In an is an integer just as 2 and i are. (Not all an integer value; we will take this up in Chapter 4.) declares the parameter types and names, and the type of the result that the function function: other routines can use the same names without will generally use parameter for a variable named in the list in a value that power computes is returned to main by the return: function need not return a value; a return statement with no causes control, but no useful value, to be returned to the caller, as does ``falling off the end'' of a function by And the calling function can ignore a value returned by like any other, it may return a value to its caller, which is in effect the we have omitted return from our main functions up to this point, but just before main says that power is a function that expects two int arguments and returns an This which is called a function has to agree with the and It is an error if the of a function or any uses of it do not agree with its A note of history: the biggest change between ANSI C and earlier versions is how the original of C, the power function would have been int base, n; for (i = 1; i <= n; ++i) The of power at the beginning of the program would have looked like this: The new syntax of function makes it much easier for a compiler to detect errors the program of Section 1.2 to use a aspect of C functions may be to who are used to some other In C, all function arguments are passed ``by value.'' This the called function is given the values of its arguments in temporary variables rather than The parameter n is used as a temporary variable, and is counted down (a for loop that runs When it is possible to arrange for a function to modify a variable in a calling and the called function must declare the parameter to be a pointer and access the When the name of an array is used as an argument, the value By this value, the function can access and alter any 1.9 Character most common type of array in C is the array of arrays and functions to them, let's write a program that reads a set of write a separate function getline to fetch the next line of useful in other end of file; a more useful design would be to return the length of the line, or zero if Every text line has at least one even a line only a newline has This suggests a second function, copy, to copy the new line to a safe line[], int c, i; for (i=0; i < lim-1 && && c!='\n'; ++i) s[i] = c; if (c == '\n') { s[i] = c; The functions getline and copy are declared at the beginning of the program, which we main and getline through a pair of arguments and a returned the arguments are declared by the line send a value back to the caller, just as the function power returns an int; since int is the default return type, it could be functions return a useful value; others, like copy, are used only for their effect and return type of copy is void, which states that no value is puts the character '\0' (the null whose value is zero) at the end of the array it is creating, to mark the end of the string of C language: when a string constant like appears in a C program, it is stored as an array of the in the a '\0', and copies this character into the testing the length and the last character returned, main the main routine of the program so it will correctly print the Write a program to print all input lines that are longer than 80 a program to remove trailing blanks and tabs from each line of input, and Write a function that reverses the character string s. write a program that reverses its input a line at a time. are declared within main, no other function can have direct access to them. the variables in other for example, the variable i in getline is unrelated to the i in Each local variable in a function comes into existence only when the function is local variables do retain their values between calls.) Because automatic variables come and go with function they do not retain that is, variables that can be accessed by name by any they retain their values even after the functions that set them have external variable must be defined, exactly once, outside of any function; this sets aside The variable must also be declared in each function that wants to access it; this To make the concrete, let us rewrite the line, longest, and max as external and bodies of all three c, i; && != EOF && c != '\n'; = c; if (c == '\n') { line[i] = c; The external variables in main, getline and copy are defined by the first lines of the are just like of local but since they occur outside of a function can use an external variable, the name of must be made known to the function; the is the same as before except variable occurs in the source file before its use in a function, then there is no need for an extern in the at the beginning of the source file, and then omit all extern the program is in several source files, and a variable is defined in file1 and used in file2 and The usual practice is to collect extern of variables and functions in a The functions of the with older C programs the standard takes an empty list as an or assigned storage; refers to places where the nature of the variable too heavily on external variables is fraught with peril since it leads to programs of two useful functions by writing into them the names of the variables of building blocks, it's possible to write useful programs of size, and it Write a program detab that replaces tabs in the input with the proper n be a variable or a symbolic a program entab that replaces strings of blanks by the minimum a program to ``fold'' long input lines into two or more shorter lines after the last non-blank character that occurs before the n-th column of does something with very long lines, and if there are no blanks or a program to remove all comments from a C quoted strings and character constants a program to check a C program for syntax errors 2 - Types, Operators and constants are the basic data objects in a variables to be used, and state what type they have and perhaps what their initial values combine variables and constants C practice is to use lower case for variable names, and all For function names only for 6 and a single int, float, etc., are reserved: you can't use them as variable for instance, if chars are 8 bits, unsigned char variables have type long double specifies floating a program to determine the ranges of char, short, int, and both signed and unsigned, by printing values from standard integer constant like 1234 is an int. as in an integer constant too big to fit into an int will also be taken as a long. is an unsigned long constant with value 15 character constant is an integer, written as one character within single quotes, such as The value of a character constant is the numeric value of the character in the set. For example, in the ASCII character set the character constant '0' has the value If we write '0' instead of a numeric value like 48 that depends on the character set, the program is of the value constants in numeric just as any other can be in character and string constants by escape \n these sequences look like two but represent only one. The character constant '\0' the character with value zero, the null often written instead of 0 to emphasize the character nature of some but the A string constant, or string literal, is a sequence of zero or more by used in character constants apply in strings; \" the a string constant is an array of standard library function strlen(s) returns the length of its character and other string functions are declared in the standard header careful to between a character constant and a string that contains a of the letter x in the machine's character set. The latter is an array of integer values, as in provide a way to associate constant values with names, an types may be declared, compilers need not check that what you store in such a variable is values of variables in their symbolic form. A specifies a type, and contains a list of one or more variables of that char c, c; before the program starts and the must be a constant automatic variable is each time the function or block it is in is The qualifier const can be applied to the of any variable to specify that its value The const can also be used with array to indicate that the operators have lower than so an like i Most C programs rely on these getline that we wrote in Chapter 1: for (i=0; i < lim-1 && != '\n' && c != EOF; ++i) s[i] = the call and must occur before the character in c is so like i < lim-1 && != '\n' && c != != '\n' to achieve the desired result of to c and then with '\n'. By the numeric value of a or logical is 1 if the relation is an operator has operands of different types, they are converted to a common an integer into floating point in an like f + like assigning a longer integer type to a shorter, or a type to an by this naive of the function atoi, which converts a string of digits into its int i, n; n = 0; return n; gives the numeric value of the character stored in s[i], because the values of '0', '1', example of char to int is the function lower, which maps a to lower case for the ASCII character set. /* lower: convert c to lower case; ASCII only */ int lower(int c) return c + 'a' - c; The standard header described in Appendix B, defines a family of functions tests and that are of character set. For example, the will use the <ctype.h> functions from now on. There is one subtle point about the of to whether variables of type char are signed or unsigned of C that any character in the machine's standard printing will never be negative, so these will always be positive in arbitrary bit patterns stored in character variables may appear to be negative on some sets d to 1 if c is a digit, and 0 if functions like isdigit may return any that floats in an are not converted to double; this is take place across the value of the right side is converted to the type A character is converted to an integer, either by sign extension or not, as described c; i = c; c = i; the value of c is a double is converted to float, whether the value is Since an argument of a function call is an type also takes place are passed to is why we have declared function arguments to be int and double even when the function is called with char and name) the is converted to the named type by the rules of a cast is as if the were assigned to a variable of the specified type, in So if n is an integer, we can use to convert the value of n to double before passing it to of n in the proper type; n itself is not arguments are declared by a function as the normally should be, the automatic coercion of any arguments when the function is a function htoi(s), which converts a string of an optional 0x or 0X) into its integer value. C provides two unusual operators for and (c == as in ++n), or postfix operators (after the variable: n++). But the ++n n before its value is used, while n after its value has been used. If n is 5, then applied to an like (i+j)++ is (c == '\n') For instance, consider the function which removes all the character c from the string s. void s[], int c) if (s[i] != c) if (s[i] != c) { if (c == '\n') { s[i] = c; if (c == = c; As a third example, consider the standard function which the As we have written it, strcat returns no value; the standard library the function which returns the first location in a string s1 (The standard library function strpbrk does the same job but returns a pointer to the C provides six operators for bit these may only be applied to integral bitwise AND operator & is often used to mask off some set of bits, for example sets to zero all but the low-order 7 bits of n. the value of x by two filling vacated bits with zero; this is to The unary operator ~ yields the one's of an integer; that is, it converts each 1-bit As an of some of the bit consider the function the (right adjusted) n-bit field of x that begins at position 0 is at the right end and that n and p are sensible positive x, int p, int n) return (x >> (p+1-n)) & ~(~0 << n); The x >> (p+1-n) moves the desired field to the right end of the a function that returns x with the n bits that begin at Write a function that returns x with the n bits that begin at Write a function that returns the value of the integer x Operators and an example, the function bitcount counts the number of 1-bits in its integer the argument x to be an unsigned ensures that when it is vacated bits will be filled with zeros, not sign bits, of the machine the program is run on. We have already seen that the statement has a value and can occur in other operators (+=, -=, etc.) can also occur in although this and that is the value of the a float and n an int, then the (n > 0) ? is of type float of whether n is example, this loop prints n for (i = 0; i < n; a[i], (i%10==9 || i==n-1) ? '\n' : ' the function lower, which converts upper case letters to lower on the same line have the same () refers to operators -> and . implies that like C, like most does not specify the order in which the operands of an operator the order in which function arguments are evaluated is not so calls, nested and increment and decrement operators effects'' - some variable is changed as a of the of an take place within an is left to the of the compiler, since the best on arguments take effect before a function is called, but that would not help in the call to The moral is that writing code that depends on order of is a bad such as x = 0 or i++ or becomes a statement when it is C, the semicolon is a statement rather than a separator as it is in languages like that surround the of a function are one obvious example; braces around if-else statement is used to express a non-zero value), is an if tests the numeric value of an certain coding shortcuts are (n > 0) if (n > 0) { if (n > 0) for (i = 0; i < n; i++) This is because a statement follows the if, and an statement like ``z if an is true, the statement with it is executed, and this returns the position (a number between 0 and n-1) if x occurs in v, and -1 if search first compares the input value x to the middle element of the array v. int x, int v[], int n) The switch statement is a multi-way decision that tests whether an matches one of a number of constant integer values, and branches case is labeled by one or more constants or constant the value, execution starts at that case. In Chapter 1 we wrote a program to count the of each digit, white space, and all Here is the same c, i, nwhite, nother, a function that converts like newline and tab escape sequences like \n and \t as it copies the string t to for the other direction as well, escape sequences into the real it is non-zero, statement is executed and is re- and expr3 are or function calls and expr2 is a ((c = == ' ' || c == '\n' || c = '\t') for (i = 0; i < n; is the C idiom for the first n elements of an array, the analog of the structure of the program reflects the form of the input: int i, n, sign; The standard library provides a more elaborate function strtol for of strings to The following function is a Shell sort for sorting an array of final C operator is the comma ``,'', which most often finds use in the for of separated by a comma is evaluated left to right, and the type and value of the result are the type and value of the right c, i, j; c = s[i]; The commas that separate function variables in etc., are not Write a function that expands shorthand notations like a-z in and digits, and be prepared to handle cases like a-b-c and a-z0-9 and -a-z. By contrast, the third loop in C, the do-while, tests at the bottom after making each pass The statement is executed, then is itoa: convert n to in s */ void itoa(int n, char the largest negative number, that is, the value of n equal to the function that converts the integer n into a base b The following function, trim, removes trailing blanks, tabs and newlines from the end of a int n; s[n+1] = n;