📄 usingc.txt
字号:
that it doesn't crash), and the student has absolutely no clue as towhat went wrong.In addition to the problem of requiring an obscure calling convention,scanf has several other properties that tend to be at least asconfusing. One significant problem is that scanf makes error recoverydifficult to perform. The return value from scanf indicates only thenumber of matching fields, and it is impossible to determine easily, forexample, whether there was extra text on the input line. If the resultis zero, indicating that no value has been read, how does the programmerrecover from that condition, particularly with respect to clearing textfrom the current line? A second problem is that using scanf requiresthe student to have a much more detailed knowledge of how the inputsystem handles special characters. If scanf is used to read an integerfrom the console, and the user terminates that input by typing thenewline character, scanf will read the terminating newline and then putit back in the input buffer using ungetc. If the student then tries toperform character input, that newline will be the first character read.This behavior is extremely difficult to explain to the novice. In fact,all of these problems are beyond the scope of an introductory treatment,and there is no way to give beginning students a complete explanation.In order to understand how to solve this problem in a classroom setting,the key is to recognize what experienced programmers do when theyencounter similar problems in the process of developing software. Asprogrammers, we often encounter situations in which the detailsnecessary to implement a conceptually simple operation turn out to bemessy. When this occurs, the standard approach is to hide thecomplexity by defining a new function or procedure that encapsulates thecomplexity and provides to its caller a clean and simple interface.I believe that this same approach offers an ideal mechanism fordeferring discussion of C's more confusing features until students areable to make sense of them. In the specific case of scanf, for example,one can mask the complexity by defining a new library that provides asimplified I/O capability. In the course at Stanford, the interface tothat library was provided by the header file "simpio.h", which gavestudents access to the functions GetInteger and GetFloat, which read andreturn an integer and floating-point value, respectively. Armed withthis library, students read integer values by writing value = GetInteger();This call takes the place of the earlier scanf construction and hasseveral advantages from the point of view of student understanding.First, it is consistent with every other type of function that they see,and its use involves no special syntactic "rules" that the compilercannot check. Second, the library implementation offers much bettererror checking and built-in recovery operations. Third, theimplementation is defined so that GetInteger always reads a completeline, and there is therefore never any confusion about whether theterminating newline character remains in the input pipeline. All inall, students understand this mechanism much more easily, and can use itwithout any significant difficulty. The scanf function is thenintroduced at a more appropriate point in the course, when it is alsopossible to expose the implementation of the "simpio.h" interface.I also used the course libraries to remedy other pedagogical problemsthat tend to arise when using C. For example, C includes no Booleantype -- an omission that has serious negative implications for teaching.Although the use of integers for this purpose might be acceptable forexperienced programmers, it has the effect of muddying completely one ofthe central concepts that introductory students must master. In mycourse, I solved the dilemma by defining the type bool as an enumerationconsisting of the constants FALSE and TRUE, and then putting thatdefinition in a standard library that students use from the verybeginning of the course. When the topic of Boolean data was firstmentioned, I noted in passing that the type bool is an extensionprovided by the library. Once that was said, I didn't mention it againfor the rest of the quarter. For my students, there is quite definitelya Boolean type. Every condition they see, and every condition theywrite has a proper Boolean form; the traditional C shortcuts that dependon the equivalence of FALSE and zero never arise. This approach leadsto a much better conceptual understanding of how to use Booleans andimproves programming style and practice.The standard library used with the course also includes an error-handling facility that makes it easy for students to think about error-checking and other defensive programming strategies early in the course.In the beginning, the error-handling facility is used simply to providea uniform mechanism for reporting errors and then terminating theprogram. Later in the course, I introduce more advanced facilities ofthe error-handling package that allow students to trap those errors andspecify recovery actions, without changing the basic discipline. Thefacility is based on a more general exception-handling mechanism for C[Roberts87].4. REACTIONS TO THE LIBRARY APPROACHIn reading through reviews of an introductory text based on thisapproach, I was interested to find that the early introduction oflibraries, such as the "simpio.h" facility outlined in the precedingsection, proved to be rather controversial. Several reviewers respondedvery favorably, noting that no other textbook addresses the problem thatstudents are not prepared to handle C constructs in their fullgenerality. Other reviewers, however, expressed strongly negativereactions to my tactic of introducing specialized abstractions, such asthe use of GetInteger and GetFloat to mask the complexity of scanf.These reviewers argued that I was changing the language or that I waslikely to distract the students by providing a mechanism that they would"remember after the course is over, instead of remembering scanf." Onereader felt sufficiently strongly about this question to set an entiresentence in italics: "If you're going to teach ANSI C, teach ANSI C, notsome modified local version of the language!"I believe that the last comment cuts to the heart of the controversy. Iwas not trying to teach ANSI C. I was trying to teach programming. Ijust happened to be using ANSI C because I believe that students wholearn programming using ANSI C will be better practitioners in the Cenvironment after they complete the course.CS1 is not a language course alone. Although learning a programminglanguage is an essential component of the introductory presentation,there are many aspects of an introductory course that are entirelyindependent of language choice. Of these, one of the most important isprocedural abstraction as a technique for managing complexity. Studentsneed to learn how to take a complex operation and encapsulate it as aprocedure call with a simple and consistent interface. The fact thatour course follows its own advice with respect to library developmentencourages students to do the same.Last year's experimental course was extremely effective in gettingstudents to recognize the value of abstraction. We introduced separatecompilation early and emphasized the importance of well-specifiedinterfaces as the link between the implementer of a module, whounderstands the details, and the client of that module, who understandsonly the abstract effect. Our students had the standard troubles withalgorithms, problem solving, implementation details, and debugging, butthey did come to master the notion of an interface and recognize itsimportance. And the concept seemed to stay with them. One of mystudents wrote to me a year later: I want to let you know that I've applied with great success your libraries in the courses I've taken . . .; it's a great concept of yours to deal with abstractions so that when you design a package, you, the "client" are relieved of the underlying implementation and can concentrate on the particular algorithms of your particular program.I don't, of course, claim credit for the concept, but I do believe thatthe pedagogical emphasis on abstraction has paid off.5. EMPHASIZING GOOD PRACTICEA second common concern is that C -- by virtue of the very power andflexibility that have ensured its commercial success -- is far too greata temptation for the beginning student. C has a reputation as thelanguage of the hacker, a domain in which all concern for goodprogramming style or sound engineering practice are inevitably displacedby a passion for writing the shortest possible program or the programthat generates the most efficient possible code. This view is sometimesencouraged by the pedagogical treatment. In the years that C wasintroduced in the "Programming Paradigms" course, the focus was on thenitty-gritty details of C, such as pointer/array equivalence, theincrement/decrement operators, and the various syntactic shortcuts forwhich C is notorious -- precisely the features students are most likelyto abuse. One of the traditional handouts used in the course was titled"C Gets Ugly," and it is not hard to imagine that some students wouldturn this assessment into a self-fulfilling prophecy.My own view is that the power of C is most destructive precisely when weteach students to use good programming techniques in some other languageand then expect them to pick up C on their own. It is at this pointthat the temptation of power seems most seductive. By teaching themgood programming style and emphasizing the importance of discipline aswe teach them about the language, we can produce solid programmers whocarry these skills forward to more advanced work.Brian Reid, who was a professor at Stanford for several years, capturedthe dilemma presented by the power of C in the simple observation:"power tools can kill." In designing a new curriculum, a department hasthe choice of (1) avoiding the use of such power tools until studentsreach upper-level courses or (2) offering courses that includeappropriate "power tool safety" components at the introductory level.We decided to opt for the second approach.I believe it is useful to remember the following observation made byLarry Flon, then at Carnegie Mellon [Flon75]: There does not now, nor will there ever, exist a programming language in which it is the least bit hard to write bad programs.The key to writing good programs, just as much today as in 1975, is gooddiscipline. If we teach that discipline, we will produce goodprogrammers. If we do not, the choice of language barely matters.6. CONCLUSIONSOver a two-year period, the Stanford Department of Computer Science hasredesigned its introductory course to use ANSI C, replacing Pascal asthe language of instruction. To avoid some of the problems thatordinarily accompany the use of C, we have adopted three strategies.First, the course defers the introduction of some of the more difficultfeatures of the language by using libraries to encapsulate thecomplexity of those features so that the student sees them only througha simple abstract interface. Second, we emphasize the idea ofprocedural abstraction and modular interfaces from the very beginning ofthe course, so that students themselves develop the skills necessary tomanage complexity when it arises. Third, we focus throughout the courseon the discipline of software engineering, so that students come torecognize -- and then to demonstrate by following our example -- that Cprograms can be written so that they are elegant, clearly presented,well-documented, and easily maintained.REFERENCES[Abelson85] Harold Abelson and Gerald Sussman, with Julie Sussman, Structure and Interpretation of Computer Programs, Cambridge: MIT Press, 1985.[Flon75] Lawrence Flon, "On research in structured programming," SIGPLAN Notices, Vol. 10, No. 10, October 1975.[Frank90] Thomas S. Frank and James F. Smith, "Ada as a CS1-CS2 language," SIGCSE Bulletin, Vol. 22, No. 2, June 1990.[Gabrini86] Philippe Gabrini, J. Mack Adams, Barry Kurtz, "Converting from Pascal to Modula-2 in the Undergraduate Curriculum," Proceedings of the Seventeenth SIGCSE Technical Symposium on Computer Science Education, February 1986.[Kernighan88] Brian Koffman and Dennis Ritchie, The C Programming Language, second edition, Englewood Cliffs: Prentice Hall, 1988.[Koffman84] Elliot B. Koffman, Philip Miller, and Caroline Wardle, "Recommended Curriculum for CS1, 1984," Communications of the ACM, Vol. 27, No. 10, October 1984.[Koffman88] Elliot B. Koffman, "The case for Modula-2 in CS1 and CS2," Proceedings of the Nineteenth SIGCSE Technical Symposium on Computer Science Education, February 1988.[Mody91] R. P. Mody, "C in Education and Software Engineering," SIGCSE Bulletin, Vol. 23, No. 3, September 1991.[Roberts89] Eric Roberts, "Implementing Exceptions in C," Research Report #40, Digital Equipment Corporation/Systems Research Center, Palo Alto, California, March 1989.[Winslow89] Leon Winslow and Joseph Lang, "Ada in CS1," Proceedings of the Twentieth SIGCSE Technical Symposium on Computer Science Education, February 1989.
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -