Chapter 1: A Tutorial Introduction
1.1 Getting Started
A C program 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. "main" is special, your program begins executing at the begining of main.
In C, the program to print "hello, world" is
#include<stdio.h> // include information about standard input/output library main() // define a function named main that receives no arguments 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 }
A sequence of characters in double quotes, like "hello world\n", is called a character string or string constant.
An escape sequence like \n provides a general and extensible mechanism for representing hard-to-type or invisible characters. C provides: \n for newline, \t for tab, \b for backspace, \" for the double quote, and \\ for the backslash iteslef.
1.2 Variables and Arithmetic Expressions
In C, all variables must be declared before they are used, usually at the begining of the function before any executable statements. A declaration announces the properties of variables; it consists of a type name and a list of variables. C provides several basic data types: int, float, char, short, long, double. The sizes of these objects are machine-dependent.
If an arithmetic operator has one floating-point operand and one integer operand, however, the integer will be converted to floating point before the operation is done. Integer division truncates: any fractional part is discarded.
1.3 The For Statement
The for statement is a loop, a generalization of the while. Within the parentheses, there are three parts, separted by semicolons. The first part, the initialization is done once, before the loop proper is entered. The second part is the test or condition that controls the loop. This condition is evaluated: if it is true, the body of the loop is executed. Then the increment step 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.
1.4 Symbolic Constants
A #define line defines a symbolic name or symbolic constant to be a particular string of characters:
#define name replacement-text
Thereafter, any occurrence of name (not in quotes and not part of another name) will be replaced by the corresponding replacement-text.
1.5 Character Input and Output
The model of input and output supported by the standard library is very simple. Text input and output, regardless of where it originates or where it goes to, is dealt with as streams of characters. A text stream is a sequence of characters divided into lines; each line consists of zero or more characters followed by a newline character.
c = getchar() reads the next input character from a text stream and returns that as its value. putchar(c) prints a character each time it is called.
EOF, "end of file", is an integer defined in <stdio.h>, but the specific numeric value doesn't matter as long as it is not be the same as any char value. getchar() return EOF when there is no more input.
In C, any assignment is an expression and has value, which is the value of the left hand side after the assignment.
The isolated semicolon, called a null statement.
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. '\n' is a single character, and in expression is just an integer; "\n" is a string constant that happens to contain only one character.
#include<stdio.h> #define IN 1 /* inside a word */ #define OUT 0 /* outside a word */ /* count lines, words, and characters in input */ main() { int c, nl, nw, nc, state; state = OUT; while ((c = getchar()) != EOF) { ++nc; if (c == '\n') ++nl; if (c == ' ' || c == '\n' || c == '\t') state = OUT; else if (state == OUT) { state = IN; ++nw; } } printf("%d %d %d\n", nl, nw, nc); }
1.6 Arrays
Array subscripts always start at zero in C. A subscript can be any integer expression, which includes integer variables and integer constants.
1.7 Functions
With properly designed functions, it is possible to ignore how a job is done; knowing what is done is sufficient. A function definition has this form:
return-type function-name(parameter declarations, if any) { declarations statements }
We will generally use parameter for a variable named in the parenthesized list in a function, and argument for the value used in a call of the function. The terms formal argument and actual argument are sometimes used for the same distinction.
return expression. A return value of zero implies normal termination; non-zero values signal unusual or erroneous termination conditions.
The declaration int power(int m, 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. Parameter names are optional in a function prototype.
1.8 Arguments - Call by value
In C, all function arguments are passed "by value". This means that the called function is given the values of its arguments in temporary variables rather than the orginals. The main distinction is that in C the called function cannot directly alter a variable in the calling function; it can only alter its private, temporary copy. When necessary, it is possible to arrange for a function to modify a variable in a calling routine. The caller must provide the address of the variable to be set (technically a pointer to the variable), and the called function must declare the parameter to be a pointer and access the variable indirectly through it.
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 acess and alter any element of the array.
1.9 Character Arrays
The return type void, which states explicitly that no value is returned.
When a string constant like "hello\n" appears in a C program, it is stored as an array of characters containing the characters of the string and terminated with a '\0' to mark the end.
The %s format specification in printf expects the corresponding argument to be a string represented in this form.
1.10 External Variables and Scope
Each local variable in a function comes into existence only when the function is called, and disappears when the function is exited.
Define variables that are external to all functions, that is, variables that can be accessed by name by any function. 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.
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. One way to do this is to write an extern declaration in the function, the declaration is the same as before except for the added keyword extern. Other way is to place definitions of all external variables at the begining of the source file, and then omit all extern declarations.
If the programs 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 declartions 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 .h is conventional for header names. The functions of the standard library, for example, are declared in headers like <stdio.h>.
The word void must be used for an explicitly empty arguments list.
Definition refers to the place where the variable is created or assigned storage; Declaration refers to places where the nature of the variable is stated but no storage is allocated.
Relying too heavily on external variables is fraught with peril since it leads to programs whose data contections are not at all obvious - variables can be changed in unexpected and even inadvertent ways, and the program is hard to modify.

浙公网安备 33010602011771号