⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 chapter1.html

📁 Kernighan and Ritchie - The C Programming Language c程序设计语言(第二版)称作是C语言学习的圣经
💻 HTML
📖 第 1 页 / 共 5 页
字号:
<html><head><title>Chapter 1 - A Tutorial Introduction</title></head><body><hr><p align="center"><a href="intro.html">Back to Introduction</a>&nbsp;--&nbsp;<a href="kandr.html">Index</a>&nbsp;--&nbsp;<a href="chapter2.html">Chapter 2</a><p><hr><h1>Chapter 1 - A Tutorial Introduction</h1>Let us begin with a quick introduction in C. Our aim is to show theessential elements of the language in real programs, but without gettingbogged down in details, rules, and exceptions. At this point, we are nottrying to be complete or even precise (save that the examples are meant to becorrect). We want to get you as quickly as possible to the point where youcan write useful programs, and to do that we have to concentrate on thebasics: variables and constants, arithmetic, control flow, functions, and therudiments of input and output. We are intentionally leaving out of thischapter features of C that are important for writing bigger programs. Theseinclude pointers, structures, most of C's rich set of operators, severalcontrol-flow statements, and the standard library.<p>This approach and its drawbacks. Most notable is that the complete story onany particular feature is not found here, and the tutorial, by being brief,may also be misleading. And because the examples do not use the full power ofC, they are not as concise and elegant as they might be. We have tried tominimize these effects, but be warned. Another drawback is that laterchapters will necessarily repeat some of this chapter. We hope that therepetition will help you more than it annoys.<p>In any case, experienced programmers should be able to extrapolate from thematerial in this chapter to their own programming needs. Beginners shouldsupplement it by writing small, similar programs of their own. Both groupscan use it as a framework on which to hang the more detailed descriptionsthat begin in <a href="chapter2.html">Chapter 2</a>.<h2><a name="s1.1">1.1 Getting Started</a></h2>The only way to learn a new programming language is by writing programs init. The first program to write is the same for all languages:<br>&nbsp;<em>Print the words</em><br>&nbsp;<tt>hello, world</tt><p>This is a big hurdle; to leap over it you have to be able to create theprogram text somewhere, compile it successfully, load it, run it, and findout where your output went. With these mechanical details mastered,everything else is comparatively easy.<p>In C, the program to print ``<tt>hello, world</tt>'' is<pre>   #include &lt;stdio.h&gt;   main()   {     printf("hello, world\n");   }</pre>Just how to run this program depends on the system you are using. As aspecific example, on the UNIX operating system you must create the programin a file whose name ends in ``<tt>.c</tt>'', such as <tt>hello.c</tt>, thencompile it with the command<pre>   cc hello.c</pre>If you haven't botched anything, such as omitting a character or misspellingsomething, the compilation will proceed silently, and make an executable filecalled <tt>a.out</tt>. If you run <tt>a.out</tt> by typing the command<pre>   a.out</pre>it will print<pre>   hello, world</pre>On other systems, the rules will be different; check with a local expert.<p>Now, for some explanations about the program itself. A C program, whateverits size, consists of <em>functions</em> and <em>variables</em>. A functioncontains <em>statements</em> that specify the computing operations to be done,and variables store values used during the computation. C functions are likethe subroutines and functions in Fortran or the procedures and functions ofPascal. Our example is a function named <tt>main</tt>. Normally you are atliberty to give functions whatever names you like, but ``<tt>main</tt>'' isspecial - your program begins executing at the beginning of main. This meansthat every program must have a <tt>main</tt> somewhere.<p><tt>main</tt> will usually call other functions to help perform its job, somethat you wrote, and others from libraries that are provided for you. Thefirst line of the program,<pre>   #include &lt;stdio.h&gt;</pre>tells the compiler to include information about the standard input/outputlibrary; the line appears at the beginning of many C source files. Thestandard library is described in <a href="chapter7.html">Chapter 7</a> and<a href="appb.html">Appendix B</a>.<p>One method of communicating data between functions is for the callingfunction to provide a list of values, called <em>arguments</em>, to the functionit calls. The parentheses after the function name surround the argument list.In this example, <tt>main</tt> is defined to be a function that expects noarguments, which is indicated by the empty list <tt>( )</tt>.<p><hr><pre>#include &lt;stdio.h&gt;                 <em>include information about standard library</em>main()                                          <em>define a function called main</em>                                             <em>that received no argument values</em>{                                   <em>statements of main are enclosed in braces</em>    printf("hello, world\n");              <em>main calls library function printf</em>                                         <em>to print this sequence of characters</em>}                                         \n <em>represents the newline character</em></pre><p align="center"><strong>The first C program</strong><p><hr><p>The statements of a function are enclosed in braces <tt>{ }</tt>.The function <tt>main</tt> contains only one statement,<pre>   printf("hello, world\n");</pre>A function is called by naming it, followed by a parenthesized list ofarguments, so this calls the function <tt>printf</tt> with the argument<tt>"hello, world\n"</tt>. <tt>printf</tt> is a library function that printsoutput, in this case the string of characters between the quotes.<p>A sequence of characters in double quotes, like <tt>"hello, world\n"</tt>, iscalled a <em>character string</em> or <em>string constant</em>. For themoment our only use of character strings will be as arguments for<tt>printf</tt> and other functions.<p>The sequence <tt>\n</tt> in the string is C notation for the <em>newlinecharacter</em>, which when printed advances the output to the left margin onthe next line. If you leave out the <tt>\n</tt> (a worthwhile experiment),you will find that there is no line advance after the output is printed. Youmust use <tt>\n</tt> to include a newline character in the <tt>printf</tt>argument; if you try something like<pre>   printf("hello, world   ");</pre>the C compiler will produce an error message.<p><tt>printf</tt> never supplies a newline character automatically, so severalcalls may be used to build up an output line in stages. Our first programcould just as well have been written<pre>   #include &lt;stdio.h&gt;   main()   {     printf("hello, ");     printf("world");     printf("\n");   }</pre>to produce identical output.<p>Notice that <tt>\n</tt> represents only a single character. An <em>escapesequence</em> like <tt>\n</tt> provides a general and extensible mechanism forrepresenting hard-to-type or invisible characters. Among the others that Cprovides are <tt>\t</tt> for tab, <tt>\b</tt> for backspace, <tt>\"</tt> forthe double quote and <tt>\\</tt> for the backslash itself. There is a completelist in <a href="chapter2.html#s2.3">Section 2.3</a>.<p><strong>Exercise 1-1.</strong> Run the ``<tt>hello, world</tt>'' program onyour system. Experiment with leaving out parts of the program, to see whaterror messages you get.<p><strong>Exercise 1-2.</strong> Experiment to find out what happens when<tt>prints</tt>'s argument string contains <em>\c</em>, where <em>c</em> issome character not listed above.<h2><a name="s1.2">1.2 Variables and Arithmetic Expressions</a></h2>The next program uses the formula <sup>o</sup>C=(5/9)(<sup>o</sup>F-32) toprint the following table of Fahrenheit temperatures and their centigrade orCelsius equivalents:<pre>   1    -17   20   -6   40   4   60   15   80   26   100  37   120  48   140  60   160  71   180  82   200  93   220  104   240  115   260  126   280  137   300  148</pre>The program itself still consists of the definition of a single functionnamed <tt>main</tt>. It is longer than the one that printed ``<tt>hello, world</tt>'',but not complicated. It introduces several new ideas, including comments,declarations, variables, arithmetic expressions, loops , and formatted output.<pre>   #include &lt;stdio.h&gt;   /* print Fahrenheit-Celsius table       for fahr = 0, 20, ..., 300 */   main()   {     int fahr, celsius;     int lower, upper, step;     lower = 0;      /* lower limit of temperature scale */     upper = 300;    /* upper limit */     step = 20;      /* step size */     fahr = lower;     while (fahr &lt;= upper) {         celsius = 5 * (fahr-32) / 9;         printf("%d\t%d\n", fahr, celsius);         fahr = fahr + step;     }   }</pre>The two lines<pre>  /* print Fahrenheit-Celsius table      for fahr = 0, 20, ..., 300 */</pre>are a <em>comment</em>, which in this case explains briefly what the programdoes. Any characters between <tt>/*</tt> and <tt>*/</tt> are ignored by thecompiler; they may be used freely to make a program easier to understand.Comments may appear anywhere where a blank, tab or newline can.<p>In C, all variables must be declared before they are used, usually at thebeginning of the function before any executable statements. A<em>declaration</em> announces the properties of variables; it consists of aname and a list of variables, such as<pre>    int fahr, celsius;    int lower, upper, step;</pre>The type <tt>int</tt> means that the variables listed are integers; by contrastwith <tt>float</tt>, which means floating point, i.e., numbers that may have afractional part. The range of both <tt>int</tt> and <tt>float</tt> depends on themachine you are using; 16-bits <tt>int</tt>s, which lie between -32768 and+32767, are common, as are 32-bit <tt>int</tt>s. A <tt>float</tt> number istypically a 32-bit quantity, with at least six significant digits andmagnitude generally between about 10<sup>-38</sup> and 10<sup>38</sup>.<p>C provides several other data types besides <tt>int</tt> and <tt>float</tt>,including:<p><table align="center" border=1><tr><td>&nbsp;<tt>char</tt>&nbsp;  </td><td>&nbsp;character - a single byte</td><tr><td>&nbsp;<tt>short</tt>&nbsp; </td><td>&nbsp;short integer</td><tr><td>&nbsp;<tt>long</tt>&nbsp;  </td><td>&nbsp;long integer</td><tr><td>&nbsp;<tt>double</tt>&nbsp;</td><td>&nbsp;double-precision floating point&nbsp;</td></table><p>The size of these objects is also machine-dependent. There are also<em>arrays</em>, <em>structures</em> and <em>unions</em> of these basic types,<em>pointers</em> to them, and <em>functions</em> that return them, all ofwhich we will meet in due course.<p>Computation in the temperature conversion program begins with the<em>assignment statements</em><pre>    lower = 0;    upper = 300;    step = 20;</pre>which set the variables to their initial values. Individual statements areterminated by semicolons.<p>Each line of the table is computed the same way, so  we use a loop thatrepeats once per output line; this is the purpose of the <tt>while</tt> loop<pre>    while (fahr &lt;= upper) {       ...    }</pre>The <tt>while</tt> loop operates as follows: The condition in parentheses istested. If it is true (<tt>fahr</tt> is less than or equal to <tt>upper</tt>), thebody of the loop (the three statements enclosed in braces) is executed. Thenthe condition is re-tested, and if true, the body is executed again. When thetest becomes false (<tt>fahr</tt> exceeds <tt>upper</tt>) the loop ends, andexecution continues at the statement that follows the loop. There are nofurther statements in this program, so it terminates.<p>The body of a <tt>while</tt> can be one or more statements enclosed in braces,as in the temperature converter, or a single statement without braces, as in<pre>   while (i &lt; j)       i = 2 * i;</pre>In either case, we will always indent the statements controlled by the <tt>while</tt> by one tab stop (which we have shown as four spaces) so you can see ata glance which statements are inside the loop. The indentation emphasizes thelogical structure of the program. Although C compilers do not care about how

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -