1. Trang chủ
  2. » Công Nghệ Thông Tin

Introduction to Computing Systems: From Bits and Gates to C and Beyond. 2nd Edition

629 929 1

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 629
Dung lượng 13,08 MB

Nội dung

introduction to computing systems The McGraw-Hill Companies Mc Graw Hill INTRODUCTION TO COMPUTING SYSTEMS: FROM BITS AND GATES TO C AND BEYOND SECOND EDITION International Edition 2005 Exclusive rights by McGraw-Hill Education (Asia), for manufacture and export This book cannot be re-exported from the country to which it is sold by McGraw-Hill The International Edition is not available in North America Published by McGraw-Hill, a business unit of The McGraw-Hill Companies, Inc., 1221 Avenue of the Americas, New York, NY 10020 Copyright © 2004, 2001 by The McGraw-Hill Companies, Inc All rights reserved No part of this publication may be reproduced or distributed in any form or by any means, or stored in a database or retrieval system, without the prior written consent of The McGrawHill Companies, Inc., including, but not limited to, in any network or other electronic storage or transmission, or broadcast for distance learning Some ancillaries, including electronic and print components, may not be available to customers outside the United States 10 09 08 07 06 05 04 03 02 01 20 09 08 07 06 05 04 CTF SEP Cover images: ©Photodisc, AA048376 Green Abstract, AA003317 Circuit Board Detail Library of Congress Control Number: 2003051002 When ordering this title, use ISBN 007-124501-4 Printed in Singapore > > second edition introduction to computing systems from bits and gates to C and beyond Yale N Patt The University of Texas at Austin Sanjay J Patel University of Illinois at Urbana-Champaign Mc Graw Hill Higher Education Boston Burr Ridge, IL Dubuque, IA Madison, Wl New York San Francisco St Louis Bangkok Bogota Caracas Kuala Lumpur Lisbon London Madrid Mexico City Milan Montreal New Delhi Santiago Seoul Singapore Sydney Taipei Toronto To the memory of my parents, Abraham Walter Patt A"H and Sarah Clara Patt A"H, who taught me to value " l e a r n i n g " even before they taught me to ride a bicycle To Mira and her grandparents, Sharda Patel and Jeram Patel contents Preface xi Preface to the First Edition XVII 2.5 2.4.1 Binary to Decimal Conversion 27 2.4.2 Decimal to Binary Conversion 28 Operations on B i t s — P a r t I : A r i t h m e t i c 2.5.1 Welcome Aboard 1.1 W h a t W e W i l l T r y t o Do 1.2 How W e W i l l Get There 1.3 Two Recurring Themes Overflow 30 31 Operations on B i t s — P a r t I I : Logical 2.6.1 v 33 The A N D Function 33 The Notion of Abstraction 2.6.2 1.3.2 Hardware versus Software 2.6.3 The NOT Function 2.6.4 The Exclusive-OR Function 1.5 T w o Very I m p o r t a n t Ideas 1.6 2.7 The OR Function 34 35 Other Representations 36 Computers as Universal Computational 2.7.1 The Bit Vector 36 Devices 2.7.2 Floating Point Data Type 2.7.3 A S C I I Codes 2.7.4 Hexadecimal Notation How Do W e Get the Electrons t o Do the Work? 12 1.7.1 The Statement of the Problem 1.7.2 The Algorithm The Program 1.7.4 The ISA 1.7.5 The Microarchitecture 1.7.6 The Logic Circuit The Devices 15 16 3.2 16 Putting I t Together 43 The Transistor Logic Gates 3.2.1 16 17 Bits and Data Types 2.1.2 41 Digital Logic Structures 3.1 Bits, Data Types, and Operations 21 2.1.1 Exercises 37 40 14 14 1.7.7 Exercises 13 35 13 1.7.3 1.7.8 2.2 Sign-Extension 2.5.3 29 1.3.1 A Computer System 2.1 2.5.2 Operations 1.4 1.7 2.6 Addition and Subtraction 3.3 21 51 51 53 The NOT Gate (Inverter) 3.2.2 OR and NOR Gates 3.2.3 A N D and N A N D Gates 3.2.4 DeMorgan's Law 3.2.5 Larger Gates 54 Decoder 3.3.2 Mux 56 58 58 Combinational Logic Circuits 3.3.1 53 59 59 60 The Bit as the Unit of 3.3.3 Full Adder Information 3.3.4 The Programmable Logic Array 21 Data Types 22 Integer Data Types 23 2.2.1 Unsigned Integers 2.2.2 Signed Integers (PLA) 3.3.5 23 2's Complement Integers 2.4 Binary-Decimal Conversion 25 27 63 Logical Completeness Basic Storage Elements 3.4.1 23 2.3 3.4 61 The R-S Latch 64 3.4.2 The Gated D Latch 3.4.3 A Register 66 64 64 66 29 vi Contents 3.5 3.6 The Concept of M e m o r y 5.4 67 68 5.4.1 Conditional Branches 3.5.2 Addressability 68 5.4.2 An Example 3.5.3 A 2 - b y - - B i t Memory 5.4.3 Two Methods f o r Loop Control 5.4.4 Example: Adding a Column of Sequential Logic Circuits 68 70 3.6.1 A Simple Example: The Combination 3.6.2 The Concept of State 3.6.3 Finite State Machines 3.6.4 An Example: The Complete 72 74 5.5 77 The Data Path of the LC-3 Exercises 5.4.5 The J M P Instruction 5.4.6 The TRAP Instruction 4.2 Basic Components 4.1.1 Memory 4.1.2 Processing Unit 4.1.3 Input and Output 4.1.4 Control Unit 4.4 99 100 The Instruction Cycle 4.3.1 The Instruction 103 4.3.2 The Instruction Cycle 155 6.1.1 Systematic Decomposition 6.1.2 The Three Constructs: Sequential; 6.1.3 107 6.2 108 157 The Character Count Example f r o m Debugging 6.2.1 Debugging Operations 6.2.2 Examples: Use of the Interactive Exercises 111 The LC-3 115 The I S A : Overview 164 5.1.2 Registers 116 7.2 An Assembly Language P r o g r a m 7.2.1 116 5.1.3 The Instruction Set 5.1.4 Opcodes 7.2.2 117 177 Instructions 5.1.5 Data Types Addressing Modes 5.1.7 Condition Codes 7.2.3 118 Pseudo-ops (Assembler Revisited 120 7.3 Operate Instructions 120 5.3 Data Movement Instructions PC-Relative Mode 5.3.2 Indirect Mode 5.3.3 Base+offset Mode 123 124 125 5.3.4 Immediate Mode 5.3.5 An Example 129 183 The Assembly Process 7.3.1 Introduction 185 185 7.3.2 A Two-Pass Process 7.3.3 The First Pass: Creating the Symbol Table 127 128 182 Example: The Character Count Example of Section 5.5, 118 5.2 178 179 Directives) 117 5.1.6 5.3.1 Assembly Language P r o g r a m m i n g — M o v i n g Up a Level Memory Organization 177 7.1 115 5.1.1 163 172 Assembly Language 5.1 158 162 Debugger 110 156 LC-3 Control Instructions to Chapter 5, Revisited 104 Control of the Instruction Stopping the Computer 155 Implement the Three 6.1.4 Changing the Sequence of Execution Exercises 155 Constructs 103 144 145 Problem Solving 101 Cycle 141 Conditional, Iterative 100 I n s t r u c t i o n Processing 4.4.1 4.5 98 141 5.6.2 Programming 6.1 The L C - : A n Example von Neumann Machine 4.3 97 137 Basic Components of the Data Path 97 136 5.6.1 Exercises The von Neumann Model 135 138 The Data Path Revisited 80 82 135 Another Example: Counting Occurrences of a Character 5.6 Finite State Machine 131 132 Numbers Using a Sentinel 71 Implementation of a 4.1 130 Address Space Lock 3.7 Control Instructions 3.5.1 7.3.4 185 186 The Second Pass: Generating the Machine Language Program 187 Contents 7.4 Beyond the Assembly of a Single Assembly Language P r o g r a m T R A P Routines for Handling 188 I/O 7.4.1 The Executable Image 7.4.2 More than One Object File Exercises 9.1.5 189 9.1.6 225 T R A P Routine for Halting the Computer 189 9.1.7 190 225 Saving and Restoring Registers 9.2 I/O 8.1 199 I/O Basics 199 8.1.1 Device Registers 8.1.2 Memory-Mapped I/O versus Special 8.1.3 Asynchronous versus Synchronous 8.1.4 8.2 The TRAP Routine for Character 9.2.4 202 Exercises 10.1 202 235 Library Routines 235 240 The Stack: Its Basic Structure 10.1.1 10.1.2 251 Two Example Implementations 204 10.1.3 Implementation in Memory Basic Output Registers (the DDR and 10.1.4 The Complete Picture Output t o the M o n i t o r 10.2 204 258 The Basic Output Service 8.3.3 Implementation of Memory-Mapped 10.2.2 Return f r o m the Interrupt Output 10.2.3 An Example Interrupt 206 Example: Keyboard Echo 207 A M o r e Sophisticated I n p u t Routine I n t e r r u p t - D r i v e n I/O 8.5.2 Why Have Interrupt-Driven 264 10.3.1 The Stack as Temporary 209 10.3.2 An Example 10.3.3 OpAdd, Op Mult, and OpNeg 210 10.4 261 262 A r i t h m e t i c Using a Stack Storage What Is Interrupt-Driven I/O? 259 207 209 8.5.1 I/O? 10.3 253 Initiate and Service the 8.3.2 205 252 257 I n t e r r u p t - D r i v e n I/O ( P a r t 2) 10.2.1 251 251 The S t a c k - A n Abstract Data Type 203 Routine 264 265 Data Type Conversion 265 272 10.4.1 Example: The Bogus Program: I m p l e m e n t a t i o n of M e m o r y - M a p p e d 1/0/ 10.4.2 A S C I I to Binary 273 Revisited 10.4.3 Binary to A S C I I 276 8.5.3 Generation of the Interrupt Signal Exercises + = e 211 214 215 10.5 TRAP Routines and Subroutines 219 LC-3 T R A P Routines 272 Our Final Example: The Calculator Exercises 9.1 233 PUTS: W r i t i n g a Character String to 10 And, Finally The Stack 202 Implementation of Memory-Mapped 8.3.4 230 232 202 8.2.3 the DSR) 8.6 9.2.3 the Monitor The Basic Input Service Input 8.5 The JSR(R) Instruction Basic Input Registers (the KBDR and Routine 8.4 The Call/Return Mechanism 9.2.2 9.2.5 8.2.2 8.3.1 9.2.1 200 Interrupt-Driven versus Polling the KBSR) 8.3 229 230 Input, Revisited 200 I n p u t f r o m the Keyboard 8.2.1 Subroutines 199 Input/Output Instructions vii 283 11 Introduction to Programming inC 289 219 9.1.1 Introduction 11.1 Our Objective 9.1.2 The T R A P Mechanism 220 11.2 B r i d g i n g the Gap 9.1.3 The T R A P Instruction 221 11.3 T r a n s l a t i n g High-Level Language 9.1.4 The Complete Mechanism 219 222 Programs 289 292 290 278 viii Contents 11.4 11.3.1 Interpretation 11.3.2 Compilation 11.3.3 Pros and Cons The C Compiler A Simple Example 297 13.2 Conditional Constructs 13.3 11.5.2 Formatting, Comments, and 11.5.3 The C Preprocessor 11.5.4 Input and Output Exercises Introduction 295 The Function m a i n Summary 13.1 293 11.5.1 Style 11.6 293 The C P r o g r a m m i n g L a n g u a g e 11.4.1 11.5 13 Control Structures 292 293 297 299 300 13.4 301 344 13.2.1 The if Statement 13.2.2 The i f - e l s e Statement Iteration Constructs The w h i l e Statement The f o r Statement 13.3.3 The d o - w h i l e Statement 359 of 7i 12.2 Variables 12.2.1 360 13.4.2 Problem 2: Finding Prime Numbers 13.4.3 Problem 3: Analyzing an E-mail Three Basic Data Types: int, char, 308 12.2.2 Choosing Identifiers 12.2.3 Scope: Local versus Global 12.2.4 More Examples Operators 12.3.1 311 313 314 Expressions and Statements The Assignment Operator 12.3.3 A r i t h m e t i c Operators 12.3.4 Order of Evaluation 12.3.5 Bitwise Operators 12.3.6 Relational Operators 12.3.7 Logical Operators 12.3.8 Increment/Decrement Operators 315 318 320 322 370 372 326 12.5.2 A l l o c a t i n g Space f o r Variables 12.5.3 A Comprehensive Example F u n c t i o n s in C 324 14.4 328 380 A Function w i t h a Parameter 14.2.2 Example: Area of a Ring I m p l e m e n t i n g F u n c t i o n s in C Run-Time Stack Getting I t A l l t o W o r k 14.3.3 Tying I t A l l Together 388 393 Problem 2: Pythagorean Summary Exercises 394 Problem 1: Case Conversion Triples 14.5 385 P r o b l e m S o l v i n g Using F u n c t i o n s 14.4.2 380 384 385 14.3.2 331 Variations of the Three Basic 379 14.2.1 14.4.1 332 379 14.2 324 326 397 398 399 332 Literals, Constants, and Symbolic Values 334 12.6.3 Storage Class 12.6.4 Additional C Operators Summary Exercises 370 372 14.3.1 Symbol Table 12.7 A n Example: Simple Introduction 14.3 12.5.1 12.6.2 13.5.3 14.1 322 T y i n g it A l l T o g e t h e r Types The break and continue 14 Functions 319 12.5 12.6.1 13.5.2 Summary 368 316 P r o b l e m S o l v i n g Using O p e r a t o r s Additional Topics The s w i t c h Statement 317 12.4 12.6 368 13.5.1 Exercises Expressions w i t h M u l t i p l e Operators 366 Calculator 13.6 362 Additional C Control Structures Statements 310 12.3.2 12.3.9 Address 13.5 308 double 12.3 307 307 358 Problem 1: A p p r o x i m a t i n g the Value Less than 100 Introduction 350 353 P r o b l e m S o l v i n g Using C o n t r o l 305 12.1 347 350 13.3.2 13.4.1 12 Variables and Operators 344 13.3.1 Structures 304 343 343 338 337 15 Testing and Debugging 335 336 15.1 Introduction 15.2 Types of E r r o r s 15.2.1 407 408 Syntactic Errors 409 407 395 ix Contents 15.3 15.4 15.5 15.2.2 Semantic Errors 15.2.3 Algorithmic Errors 411 17.5 Fibonacci Numbers 17.6 Binary Search 17.7 Integer t o A S C I I Black-Box Testing 412 17.8 Summary 15.3.2 White-Box Testing 413 Exercises 412 Debugging Ad Hoc Techniques 15.4.2 Source-Level Debuggers 18 I/O in C 415 417 Introduction Nailing Down the 18.2 The C Standard L i b r a r y Specification 18.3 I/O, One Character a t a T i m e 417 15.5.2 Modular Design 15.5.3 Defensive Programming Summary 418 418 419 421 16 Pointers and Arrays 16.1 Introduction 16.2 Pointers 427 427 481 18.3.1 I/O Streams 18.3.2 putchar 483 18.3.3 getchar 483 18.3.4 Buffered I/O F o r m a t t e d I/O Declaring Pointer Variables 16.2.2 Pointer Operators 16.2.3 Passing a Reference Using 429 430 printf scanf 485 18.4.3 Variable Argument 487 489 18.5 I/O f r o m Files 18.6 Summary 491 493 494 432 Null Pointers 433 16.2.5 Demystifying the Syntax 16.2.6 An Example Problem Involving 19 Data Structures Pointers 19.1 Arrays 16.3.1 434 434 436 19.2 498 Arrays 19.2.2 436 16.3.3 Arrays as Parameters 16.3.4 Strings in C 16.3.5 The Relationship Between Arrays and 438 440 441 Pointers in C 446 in C 19.4 Dynamic M e m o r y A l l o c a t i o n 19.4.1 in C Summary 510 516 449 451 451 A.l 17 Recursion 17.2 506 517 A The LC-3 ISA 17.1 504 508 An Example Summary Exercises 502 Dynamically Sized Arrays Linked Lists 19.5.1 19.6 Common Pitfalls with Arrays 501 A r r a y s of Structures 19.5 446 500 Implementing Structures 19.3 Problem Solving: Insertion Sort Exercises Structures 497 497 19.2.1 typedef Examples Using Arrays 16.3.7 Introduction Declaring and Using 16.3.2 16.3.6 483 18.4.2 Exercises 482 485 Lists 16.2.1 481 482 18.4.1 428 Pointers 16.4 481 18.1 18.4 16.3 473 414 P r o g r a m m i n g f o r Correctness 16.2.4 471 473 414 15.4.1 Exercises 464 468 15.3.1 Testing 15.5.1 15.6 409 Introduction Overview 521 523 521 457 A.2 Notation 457 A.3 The I n s t r u c t i o n Set A.4 I n t e r r u p t and Exception Processing W h a t Is Recursion? 458 17.3 Recursion versus I t e r a t i o n 17.4 Towers of Hanoi 460 459 A.4.1 Interrupts A.4.2 Exceptions 523 543 544 543 Contents X B From LC-3 to x86 B.l B.2 D.4 Declarations 595 LC-3 Features and Corresponding x D.4.1 Variable Declarations 595 Features D.4.2 Function Declarations 596 548 B.l.l Instruction Set B.l.2 Memory B.l.3 Internal State D.5 548 Operators 596 D.5.1 Assignment Operators D.5.2 Arithmetic Operators The F o r m a t and Specification of x D.5.3 Bit-wise Operators Instructions D.5.4 Logical Operators B.2.1 B.3 547 553 553 557 Prefix 558 B.2.2 Opcode B.2.3 ModR/M Byte B.2.4 S I B Byte B.2.5 Displacement B.2.6 Immediate A n Example 559 Relational Operators D.5.6 I ncrement/Decrement Operators 560 560 599 Conditional Expression D.5.8 Pointer, Array, and Structure Operators 600 D.5.9 sizeof 601 D.5.10 Order of Evaluation C The Microarchitecture of the LC-3 565 C.l Overview C.2 The State Machine 565 C.3 The Data Path C.4 The Control Structure C.5 M e m o r y - M a p p e d I/O C.6 I n t e r r u p t and Exception Control 569 569 D.6.2 Statements Control If-else 605 Switch 605 While 606 For 607 Do-while 607 Break 608 continue 608 return 609 D.7.5 579 D.7.6 C.6.2 Returning f r o m an Interrupt, D.7.7 D.7.8 581 The Illegal Opcode Exception Control Store D.8 583 D.9 D The C Programming Language 585 D.l Overview D.2 C Conventions D.2.1 585 585 Source Files 604 The C Preprocessor 609 D.8.1 Macro substitution D.8.2 File inclusion 609 610 Some Standard L i b r a r y Functions D.9.1 I/O Functions D.9.2 String Functions D.9.3 Math Functions D.9.4 Utility Functions 610 611 612 613 613 585 D.2.2 Header Files D.2.3 Comments D.2.4 Literals D.2.5 D.7.9 582 604 D.7.2 D.7.4 576 604 If D.7.3 575 603 603 D.7.1 Initiating an Interrupt C.6.3 D.3 Expressions C.6.1 RTI C.7 D.7 567 602 D.5.11 Expressions and Statements D.6.1 600 602 Type Conversions D.6 599 D.5.7 560 562 598 598 D.5.5 559 597 597 585 586 E Useful Tables 586 Formatting 588 D.2.6 Keywords Types 589 588 D.3.1 Basic Data Types D.3.2 Type Qualifiers D.3.3 Storage Class 591 D.3.4 Derived Types 592 D.3.5 typedef 594 615 E.l Commonly Used Numerical Prefixes E.2 Standard A S C I I codes E.3 Powers of 616 617 589 590 F Solutions to Selected Exercises 619 615 604 appendix d The C P r o g r a m m i n g Language The type of an expression is based on the individual elements of the expression, according to the C type promotion rules (see Section D.5.11) If all the elements of an expression are int types, then the expression is of int type Following are several examples of expressions: a * a - b * b a++ - c / a q ! | integrate : x"> D.6.2 Statements In C, simple statements are expressions terminated by a semicolon, ; Typically, statements modify a variable or have some other side effect when the expression is evaluated Once a statement has completed execution, the next statement in sequential order is executed If the statement is the last statement in its function, then the function terminates /* Two simple statements */ Related statements can be grouped togethered into a compound statement, or block, by surrounding them with curly braces, { } Syntactically, the compound statement is the same as a simple statement, and they can be used interchangeably { c = a * a + b * b ; b = a+4 - c / 3; /* One compound statement */ } 0.7 Control The control constructs in C enable the programmer to alter the sequential execution of statements with statements that execute conditionally or iteratively D.7.1 i f An if statement has the format if (expression) statement If the expression, which can be of any basic, enumerated, or pointer types, evaluates to a nonzero value, then the statement, which can be a simple or compound statement, is executed if (x < 0) a = b + c; /* Executes if x is less than zero */ See Section 13.2.1 for more examples of if statements D.7 Control D.7.2 If-else An if-else statement has the format if (expression) statement:! else statement.2 If the expression, which can be of any basic, enumerated, or pointer type, evaluates to a nonzero value, then statement! is executed Otherwise, statement2 is executed Both statement and statement2 can be simple or compound statements a = b + c; / * Executes if x is less than zero * / a - ):• - c; / * Otherwise, this is executed */ See Section 13.2.2 for more examples of if_-else statements D.7.3 Switch A switch statement has the following format: switch(expression; case const-exprl: statementlA statement 15 ( case const-expr2: stateiuer:t-2A stat ement2B case const-expx'N: statements statementNB A switch statement is composed of an expression, which must be of integral type (see Section D.3.1), followed by a compound statement (though it is not required to be compound, it almost always is) Within the compound statement exist one or more case labels, each with an associated constant integral expression, called const-exprl, const-expr2, const-exprN in the preceding example Within a switch, each case label must be different 605 606 appendix d The C P r o g r a m m i n g Language When a switch is encountered, the controlling expression is evaluated If one of the case labels matches the value of expression, then control jumps to the statement that follows and proceeds from there The special case label default can be used to catch the situation where none of the other case labels match If the def aui t case is not present and none of the labels match the value of the controlling expression, then no statements within the switch are executed The following is an example of a code segment that uses a s w i t c h statement The use of the break statement causes control to leave the s w i t c h See Section D.7.7 for more information on break c h a r k; k = getchar() ; s w i t c h (k) { case ' * ' : a ^ b + c; break; /' * b r e a k c a u s e s c o n t r o l t o l e a v e s w i t c h * / case ' - ' : a = b - c; break; case *1: a ^ b * c; break; case '/': -i a - b / c; break; See Section 13.5.1 for more examples of swircn statements D.7.4 While A while statement has the following format: while (expression) statement The while statement is an iteration construct If the value of expression evaluates to nonzero, then the statement is executed Control does not pass to the subsequent statement, but rather the expression is evaluated again and the process is repeated This continues until expression evaluates to 0, in which case control passes to the next statement The statement can be a simple or compound statement In the following example, the wnile loop will iterate 100 times X = 0; while (x < 100) { p r i n t f [ n x - %d\n", x) ; X ~ X + 1; See Section 13.3.1 for more examples of while statements D.7 Control D.7.5 For A for statement has the following format: for (initializer; s t a t emerit term-expr; reinitializer) The f o r statement is an iteration construct The initializer, which is an expression, is evaluated only once, before the loop begins The term-expr is an expression that is evaluated before each iteration of the loop If the term-expr evaluates to nonzero, the loop progresses; otherwise the loop terminates and control passes to the statement following the loop Each iteration of the loop consists of the execution of the statement, which makes up the body of the loop, and the evaluation of the reinitializer expression The following example is a for loop that iterates 100 times for (X = 0; X < 100; X++i { printf( M x = %d\n", x) ; See Section 13.3.2 for more examples of for statements D.7.6 Do-while A do-while statement has the format statement while (expression); The - while statement is an iteration construct similar to the while statement When a do-whi le is first encountered, the statement that makes up the loop body is executed first, then the expression is evaluated to determine whether to execute another iteration If it is nonzero, then another iteration is executed (in other words, statement is executed again) In this manner, a do-while always executes its loop body at least once The following do- while loop iterates 100 times printf("x = %d\n", x); \ j while (x < 100); See Section 13.3.3 for more examples of do-while statements 607 608 appendix d The C Programming Language D.7.7 Break A break statement has the format: The break statement can only be used in an iteration statement or in a switch statement It passes control out of the smallest statement containing it to the statement immediately following Typically, creak is used to exit a loop before the terminating condition is encountered In the following example, the execution of the rreak statement causes control to pass out of the f o r loop See Section 13.5.2 for more examples of break statements D.7.8 continue A continue statement has the following format: The continue statement can be used only in an iteration statement It prematurely terminates the execution of the loop body That is, it terminates the current iteration of the loop The looping expression is evaluated to determine whether another iteration should be performed In a for loop the reinitialize}' is also evaluated If the continue statement is executed, then x is incremented, and the reinitialize r executed, and the loop expression evaluated to determine if another iteration should be executed if (skip) continue; See Section 13.5.2 for more examples of c statements D.8 The C Preprocessor D.7.9 return A return statement has the format return expression; The return statement causes control to return to the current caller function, that is, the function that called the function that contains the return statement Also, after the last statement of a function is executed, an implicit return is made to the caller The expression that follows the return is the return value generated by the function It is converted to the return type of the function If a function returns a value, and yet no return statement within the function explicitly generates a return value, then the return value is undefined return x y; D.8 The C Preprocessor The C programming language includes a preprocessing step that modifies, in a programmer-controlled manner, the source code presented to the compiler The most frequently used features of the C preprocessor are its macro substitution facility (#def ine), which replaces a sequence of source text with another sequence, and the file inclusion facility (^include), which includes the contents of a file into the source text Both of these are described in the following subsections None of the preprocessor directives are required to end with a semicolon Since #def ine and ^include are preprocessor directives and not C statements, they are not required to be terminated by semicolons D.8.1 Macro Substitution The #define preprocessor directive instructs the C preprocessor to replace occurrences of one character sequence with another Consider the following example: #define A Here, any token that matches A will be replaced by B That is, the macro A gets substituted with B The character A must appear as an individual sequence, i.e., the A in APPLE will not be substituted, and not appear in quoted strings, i.e., neither will "A" The replacement text spans until the end of the line If a longer sequence is required, the backslash character, \ , can be used to continue to the next line Macros can also take arguments They are specified in parentheses immediately after the text to be replaced For example: #derine REMAINDER (X, Y) ( (X) % \Y> i 609 610 appendix d The C P r o g r a m m i n g Language Here, every occurrence of the macro COPY in the source code will be accompanied by two values, as in the following example The macro REMAINDER will be replaced by the preprocessor with the replacement text provided in the ^def,ne, and the two arguments A and B will be substituted with the two arguments that appear in the source code The previous code will be modified to the following after preprocessing: vaiueC - ((valueA^ % (valueR - 15};; Notice that the parentheses sunuundm^ X md Y in the macro definition were required Without them, the macro i: would have calculated the wrong value While the r e m a i n d e r macro appears to be similar to a function call, notice that it incurs none of the function call overhead associated with regular functions D.8.2 File Inclusion The tf include directive instructs the preprocessor to insert the contents of a file into the source file Typically, the s i n ^ u d e directive is used to attach header files to C source files C header files typically contain - d e f i n e s and declarations that are useful among multiple source files There are two variations of the sinclude directive: #include ^include " p r o g r a m h" The first variation uses angle brackets, < >, around the filename This tells the preprocessor that the header file can be found in a predefined directory, usually determined by the configuration of the system and which contains many systemrelated and library-related header files, such as stdic.h The second variation, using double quotes, n n , around the filename, instructs the preprocessor that the header file can be found in the same directory as the C source file D.9 Some Standard Library Functions The ANSI C standard library contains over 150 functions that perform a variety of useful tasks (for example, I/O and dynamic memory allocation) on behalf of your program Every installation of ANSI C will have these functions available, so even if you make use of these functions, your program will still be portable from one ANSI C platform to another In this section, we will describe some useful standard library functions D.9 Some Standard L i b r a r y Functions 622 D.9.1 I/O Functions The header file must be included in any source file that contains calls to the standard I/O functions Following is a small sample of these functions This function has the following declaration: The function gee char reads the next character from the standard input device, or stdin The value of this character is returned (as an integer) as the return value The behavior of getchar is very similar to the LC-3 input TRAP (except no input banner is displayed on the screen) Most computer systems will implement getchar using buffered I/O This means that keystrokes (assuming standard input is coming from the keyboard) will be buffered by the operating system until the Enter key is pressed Once Enter is pressed, the entire line of characters is added to the standard input stream putchar This function has the following declaration: The function putchar takes an integer value representing an ASCII character and puts the character to the standard output stream This is similar to the LC-3 TRAP OUT If the standard output stream is the monitor, the character will appear on the screen However, since many systems buffer the output stream, the character may not appear until the system's output buffer is flushed, which is usually done once a newline appears in the output stream S TTi This function has the following declaration: int scanf ; const char * format string, *ptrl, ,- The function scant: is passed a format string (which is passed as pointer to the initial character) and a list of pointers The format string contains format specifications that control how scanf will interpret fields in the input stream For example, the specification %d causes scanf to interpret the next sequence of nonwhite space characters as adecimal number This decimal is converted from ASCII into an integer value and assigned to the variable pointed to by the next pointer in the parameter list Table D.5 contains a listing of the possible specifications for use with scanf The number of pointers that follow the format string in the parameter list should correspond to the number of format specifications in the format string The value returned by scanf corresponds to the number of variables that were successfully assigned 612 appendix d The C P r o g r a m m i n g Language scanf Conversion Specifications scanf Conversions Parameter Type *i •i - decimal, octal (leading : ) , hex (leading c x or o x ) octal hexadecimal unsigned decimal char string of non-white space characters, : added floating point number double precision floating point number signed decimal lu , p r i n t f Conversion Specifications printf Conversions Printed as signed decimal octal hexadecimal ( a - f or A - F ) unsigned decimal single chatstring, terminated by floating point in decimal notation floating point in exponential notation pointer This function has the following declaration: inr printf • ccrist cnar *formatString, ;; The function printf writes the format string (passed as a pointer to the initial character) to the standard output stream If the format string contains a format specification, then print f will interpret the next parameter in the parameter list as indicated by the specification, and embed the interpreted value into the output stream For example, the format specification : : will cause printf to interpret the next parameter as a decimal value, printf will write the resulting digits into the output stream Table D.6 contains a listing of the format specifications for use with princf In general, the number of values following the format string on the parameter list should correspond to the number of format specifications in the format string, printf returns the number of characters written to the output stream However, if an error occurs, a negative value is returned D.9.2 String Functions The C standard library contains around 15 functions that perform operations on strings (that is, null-terminated arrays of characters) To use the string functions from within a program, include the ^ s t n a c b header file in each source file that contains a call to a library string function In this section, we describe two examples of C string functions D.9 Some S t a n d a r d L i b r a r y Functions 613 strcmp This function has the following declaration: int strcmp(char *stringA, char *stringB); This function compares stringA with strings It returns a if they are equal It returns a value greater than if stringA is lexicographically greater than strings (lexicographically greater means that stringA occurs later in a dictionary than stnngB) It returns a value less than if stringA is lexicographically less than strings strcpy This function has the following declaration: char *strcpy(char *stringA, char *stringB;; This function copies srringB to stringA It copies every character in strings up to and including the null character The function returns a pointer to st ringA if no errors occurred D.9.3 Math Functions The C standard math functions perform commonly used mathematical operations Using them requires including the : 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 ASCII ASCII Hex 20 21 22 23 24 25 26 27 28 29 2A B 2C 2D E F 30 31 32 33 34 35 36 37 38 39 3A 3B 3C 3D E 3F Character "r: A B £ E F '•j H I K T_ M i>I P Q •Q T U \j \\ X 'f r — Dec 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 Hex 40 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F 50 51 52 53 54 55 56 57 58 59 5A 5B 5C 5D E 5F Character a b c d e f q h i j k x y-n n G P Q" r s t u v w X v / } del Dec 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 Hex 60 61 62 63 64 65 66 67 68 69 6A 6B 6C 6D 6E 6F 70 71 72 73 74 75 76 77 78 79 7A 7B 7C 7D E 7F E.3 E.3 Powers of P o w e r s of Common Abbreviation Amount Decimal Conversion 21 22 — 23 24 25 2e 16 32 — 27 28 29 2io i i 12 13 14 15 16 217 18 19 20 30 32 64 128 256 512 1/024 2,048 4;096 8/192 16/384 32/768 65/536 131/072 262/144 544/288 1/048/576 1/073/741/824 4/294/967/296 — — — — _ — — IK 2I< 4K 8I< 16 K 32 K 641< 128K 256K 512 K IM 1G 4G Powers of Solutions to Selected Exercises Solutions to selected exercises can be found on our website: http://www.mhhe.com/patt2 [...]... basic programming concepts are mastered, it is a short step for students to learn more advanced concepts such as objects and abstraction Each time a new construct in C is introduced, the student is shown the LC-2 code that a compiler would produce We cover the basic constructs of C (variables, operators, control, and functions), pointers, recursion, arrays, structures, I/O, complex data structures, and. .. patt@ece.utexas.edu and sjp@crhc.uiuc.edu We hope you will Yale N Patt Sanjay J Patel March 2000 c h a p t e r i Welcome Aboard 1.1 What He Hill Try to Do Welcome to From Bits and Gates to C and Beyond Our intent is to introduce you over the next 632 pages to come, to the world of computing As we do so, we have one objective above all others: to show you very clearly that there is no magic to computing The computer... language, C We include many aspects of C that are usually not dealt with in an introductory textbook In almost all cases, we try to tie high-level C constructs to the underlying LC-3, so that you will understand what you demand of the computer when you use a particular construct in a C program Our treatment of C starts with basic topics such as variables and operators (Chapter 12), control structures (Chapter... and operators Chapter 13 introduces C control structures We provide many complete program examples to give students a sample of how each of these concepts is used in practice LC-2 code is used to demonstrate how each C construct affects the machine at the lower levels In Chapter 14, students are exposed to techniques for debugging high-level source code Chapter 15 introduces functions in C Students are... structures (Chapter 13), and functions (Chapter 14) We then 1.3 Two Recurring Themes 3 move on to the more advanced topics of debugging C programs (Chapter 15), recursion (Chapter 16), and pointers and arrays (Chapter 17) We conclude our introduction to C by examining two very common high-level constructs, input/output in C (Chapter 18) and the linked list (Chapter 19) 1.3 TUJO Recurring Themes Two themes... added discussions to Chapter 1 on the nature and importance of abstraction and the interplay of hardware and software because it became clear that these points needed to be made explicit We added a full section to Chapter 3 on finite state control and its implementation as a sequential switching circuit because we believe the concept of state and finite state control are among the most important concepts... covers two sophisticated LC-3 mechanisms, TRAPs and subroutines We conclude our introduction to programming the LC-3 in Chapter 10 by first introducing two important concepts (stacks and data conversion), and then by showing a sophisticated example: an LC-3 program that carries out the work of a handheld calculator In the second half of the book (Chapters 11-19), we turn our attention to a high-level... microprocessors today contain special hardware capability to process these video clips Intel defined additional instructions, collectively called their MMX instruction set, and developed 5 6 chapter 1 Welcome Aboard special hardware for it Motorola, IBM, and Apple did essentially the same thing, resulting in the AltaVec instruction set and special hardware to support it A similar story can be told about... gasket to be shipped in The second story (perhaps apocryphal) is supposed to have happened during the infancy of electric power generation General Electric Co was having trouble with one of its huge electric power generators and did not know what to do On the front of the generator were lots of dials containing lots of information, and lots of screws that could be rotated clockwise or counterclockwise... language occupies the second half of the book By the time the student gets to C, he/she has an understanding of the layers below The C programming language fits very nicely with our bottom-up approach Its low-level nature allows students to see clearly the connection between software and the underlying hardware In this book we focus on basic concepts such as control structures, functions, and arrays Once

Ngày đăng: 10/09/2016, 12:40

TỪ KHÓA LIÊN QUAN