词条 | Comparison of Pascal and C |
释义 |
}}{{ProgLangCompare}} The computer programming languages C and Pascal have similar times of origin, influences, and purposes. Both were used to design (and compile) their own compilers early in their lifetimes. The original Pascal definition appeared in 1969 and a first compiler in 1970. The first version of C appeared in 1972. Both are descendants of the ALGOL language series. ALGOL introduced programming language support for structured programming, where programs are constructed of single entry and single exit constructs such as if, while, for and case. Pascal stems directly from ALGOL W, while it shared some new ideas with ALGOL 68. The C language is more indirectly related to ALGOL, originally through B, BCPL, and CPL, and later through ALGOL 68 (for example in case of What is documented here is the Pascal of Niklaus Wirth, as standardized as ISO 7185 in 1982. The C documented is the language of Brian Kernighan and Dennis Ritchie, as standardized in 1989. The reason is that these versions both represent the mature version of the language, and also because they are comparatively close in time. ANSI C and C99 (the later C standards) features, and features of later implementations of Pascal (Turbo Pascal, Free Pascal) are not included in the comparison, despite the improvements in robustness and functionality that they conferred. Syntax{{unreferenced section|date=June 2013}}Syntactically, Pascal is much more ALGOL-like than C. English keywords are retained where C uses punctuation symbols – Pascal has Semicolon useAnother, more subtle, difference is the role of the semicolon. In Pascal semicolons separate individual statements within a compound statement whereas they terminate the statement in C. They are also syntactically part of the statement itself in C (transforming an expression into a statement). This difference manifests itself primarily in two situations:
A superfluous semicolon can be put on the last line before end, thereby formally inserting an empty statement. CommentsIn traditional C, there are only In traditional Pascal, there are Modern Pascal, like Object Pascal (Delphi, FPC), as well as modern C implementations allow C++ style comments Identifiers and keywordsC and Pascal differ in their interpretation of upper and lower case. C is case sensitive while Pascal is not, thus Both C and Pascal use keywords (words reserved for use by the language itself). Examples are if, while, const, for and goto, which are keywords that happen to be common to both languages. In C, the basic built-in type names are also keywords (e.g. int, char) or combinations of keywords (e.g. unsigned char), while in Pascal the built-in type names are predefined normal identifiers. Definitions, declarations, and blocksIn Pascal, procedure definitions start with keywords procedure or function and type definitions with type. In C, function definitions are determined by syntactical context while type definitions use the keyword In Pascal functions, begin and end delimit a block of statements (proper), while C functions use "{" and "}" to delimit a block of statements optionally preceded by declarations. C (before C99) strictly defines that any declarations must occur before the statements within a particular block but allows blocks to appear within blocks, which is a way to go around this. Pascal is strict that declarations must occur before statements, but allows definitions of types and functions - not only variable declarations - to be encapsulated by function definitions to any level of depth. ImplementationThe grammars of both languages are of a similar size. From an implementation perspective the main difference between the two languages is that to parse C it is necessary to have access to a symbol table for types, while in Pascal there is only one such construct, assignment. For instance, the C fragment Simple types{{unreferenced section|date=June 2013}}IntegersPascal requires all variable and function declarations to specify their type explicitly. In traditional C, a type name may be omitted in most contexts and the default type C accommodates different sizes and signed and unsigned modes for integers by using modifiers such as SubrangesIn Pascal, a similar end is performed by declaring a subrange of integer (a compiler may then choose to allocate a smaller amount of storage for the declared variable): type a = 1..100; b = -20..20; c = 0..100000; This subrange feature is not supported by C. A major, if subtle, difference between C and Pascal is how they promote integer operations. In Pascal, the result of an operation is defined for all integer/subrange types, even if intermediate results do not fit into an integer. The result is undefined only if it does not fit into the integer/subrange on the left hand side of the assignment. This may imply an artificial restriction on the range of integer types, or may require slow execution to handle the intermediate results: However, the compiler may take advantage of restricted subranges to produce more efficient code. In C, operands must first be promoted to the size of the required result: intermediate results are undefined if they do not fit into the range of the promoted operands. If range of the required result is greater than the range of operands, this normally produces slow inefficient code, even from a good optimising compiler. However, a C compiler is never required or expected to handle out of range intermediate results: it is the programmers responsibility to ensure that all intermediate results fit into the operand range. The (only) pre-Standard implementation of C as well as Small-C et al. allowed integer and pointer types to be relatively freely intermixed. Character typesIn C the character type is This integer nature of unsigned char uc = 255; /* common limit */ signed char sc = -128; /* common negative limit */ Whether the In Pascal, characters and integers are distinct types. The inbuilt compiler functions Boolean typesIn Pascal, boolean is an enumerated type. The possible values of boolean are false and true. For conversion to integer, ord is used: i := ord(b); There is no standard function for integer to boolean, however, the conversion is simple in practice: b := i <> 0; C has binary valued relational operators (<, >, ==, !=, <=, >=) which may be regarded as boolean in the sense that they always give results which are either zero or one. As all tests (&&, ||, ?:, if, while, etc.) are performed by zero-checks, false is represented by zero, while true is represented by any other value. Bitwise operationsC allows using bitwise operators to perform boolean operations. Care must be taken because the semantics are different when operands make use of more than one bit to represent a value. Pascal has another more abstract, high level method of dealing with bitwise data, sets. Sets allow the programmer to set, clear, intersect, and unite bitwise data values, rather than using direct bitwise operators (which are available in modern Pascal as well). Example; Pascal: Status := Status + [StickyFlag]; Status := Status - [StickyFlag]; if (StickyFlag in Status) then ... or Pascal: Status := Status or StickyFlag; Status := Status and not StickyFlag; if StickyFlag and Status = StickyFlag then ... C: Status |= StickyFlag; Status &= ~StickyFlag; if (Status & StickyFlag) { ... Although bit operations on integers and operations on sets can be considered similar if the sets are implemented using bits, there is no direct parallel between their uses unless a non-standard conversion between integers and sets is possible. A note on implementationDuring expression evaluation, and in both languages, a boolean value may be internally stored as a single bit, a single byte, a full machine word, a position in the generated code, or as a condition code in a status register, depending on machine, compiler, and situation; these factors are usually more important than the language compiled. Floating point typesC has a less strict model of floating point types than Pascal. In C, integers may be implicitly converted to floating point numbers, and vice versa (though possible precision loss may be flagged by warnings). In Pascal, integers may be implicitly converted to Enumeration typesBoth C and Pascal include enumeration types. A Pascal example: type var A C example: enum color {red, green, blue}; enum color a; The behavior of the types in the two languages however is very different. In C, Structured types{{Unreferenced section|date=June 2013}}Array typesBoth C and Pascal allow arrays of other complex types, including other arrays. However, there the similarity between the languages ends. C arrays are simply defined by a base type and the number of elements: int a[SIZE]; and are always indexed from 0 up to SIZE-1 (i.e. modulo SIZE). In Pascal, the range of indices is often specified by a subrange (as introduced under simple types above). The ten elements of would be indexed by 0..9 (just as in C in this case). Array indices can be any ordinal data type, however, not just ranges: type TColor = (red, green, blue); (* enumeration *) RGB = array[TColor] of 0..255; var picture : array[1..640, 1..480] of RGB var palette : array[byte, 0..2] of byte Strings consisting of n (>1) characters are defined as packed arrays with range 1..n. Arrays and pointersIn C expressions, an identifier representing an array is treated as a constant pointer to the first element of the array, thus, given the declarations While arrays in C are fixed, pointers to them are interchangeable. This flexibility allows C to manipulate any length array using the same code. It also leaves the programmer with the responsibility not to write outside the allocated array, as no checks are built in into the language itself. In Pascal, arrays are a distinct type from pointers. This makes bounds checking for arrays possible from a compiler perspective. Practically all Pascal compilers support range checking as a compile option. The ability to both have arrays that change length at runtime, and be able to check them under language control, is often termed "dynamic arrays". In Pascal the number of elements in each array type is determined at compile-time and cannot be changed during the execution of the program. Hence, it is not possible to define an array whose length depends in any way on program data. C has the ability to initialize arrays of arbitrary length. The static char *wordlist[] = { static int listSize = (sizeof(wordlist)/sizeof(wordlist[0])); int i; for (i=0; i for (i=listSize-1; i>=0; i--) Pascal has neither array initialization (outside of the case of strings) nor a means of determining arbitrary array sizes at compile time. One way of implementing the above example in Pascal, but without the automatic size adjustment, is: const minlist = 1; maxlist = 5; maxword = 7; type listrange = minlist .. maxlist; wordrange = 1..maxword; word = record contents: packed array [wordrange] of char; length: wordrange end; wordlist = array[listrange] of word; var i: integer; words: wordlist; procedure CreateList(var w: wordlist); begin w[1].contents := 'print '; w[1].length := 5; w[2].contents := 'out '; w[2].length := 3; w[3].contents := 'the '; w[3].length := 3; w[4].contents := 'text '; w[4].length := 4; w[5].contents := 'message'; w[5].length := 7; end; begin CreateList(words); for i := minlist to maxlist do with words[i] do WriteLn(contents: length); for i := maxlist downto minlist do with words[i] do WriteLn(contents: length) end. StringsIn both languages, a string is a primitive array of characters. In Pascal a string literal of length n is compatible with the type Pascal has no support for variable-length arrays, and so any set of routines to perform string operations is dependent on a particular string size. The now standardized Pascal "conformant array parameter" extension solves this to a great extent, and many or even most implementations of Pascal have support for strings native to the language. C string literals are null-terminated; that is to say, a trailing null character as an end-of-string sentinel: const char *p; p = "the rain in Spain"; /* null-terminated */ Null-termination must be manually maintained for string variables stored in arrays (this is often partly handled by library routines). C does not have built-in string or array assignment, so the string is not actually being transferred to p, but rather p is being made to point to the constant string in memory. In Pascal, unlike C, the string's first character element is at index 1 and not 0 (leading it to be length-prefixed). This is because Pascal stores the length of the string at the 0th element of the character array. If this difference is not well understood it can lead to errors when porting or trying to interface object code generated by both languages. FreeBSD developer Poul-Henning Kamp, writing in ACM Queue, would later refer to the victory of null-terminated strings over length-prefixed strings as "the most expensive one-byte mistake" ever.[1]Record typesBoth C and Pascal can declare "record" types. In C, they are termed "structures". struct a { int b; char c; }; type a = record b: integer; c: char; end; In Pascal, we can use the sentence "with type r = record s: string; c: char; end; var r1 : r; begin with r1 do begin s := 'foo'; c := 'b'; end; There is no equivalent feature to with in C. In C, the exact bit length of a field can be specified: struct a { unsigned int b:3; unsigned int c:1; }; How much storage is actually used depends on traits (e.g. word-alignment) of the target system. This feature is available in Pascal by using the subrange construct (3 bits gives a range from 0 to 7) in association with the keyword packed: type a = packed record b: 0..7; c: 0..1; end; Both C and Pascal support records which can include different fields overlapping each other: union a { int a; float b; }; type a = record case boolean of false: (a: integer); true: (b: real) end; Both language processors are free to allocate only as much space for these records as needed to contain the largest type in the union/record. The biggest difference between C and Pascal is that Pascal supports the explicit use of a "tagfield" for the language processor to determine if the valid component of the variant record is being accessed: type a = record case q: boolean of false: (a: integer); true: (b: real) end; In this case, the tagfield q must be set to the right state to access the proper parts of the record. PointersIn C, pointers can be made to point at most program entities, including objects or functions: int a; int *b; int (*compare)(int c, int d); int MyCompare(int c, int d); b = &a; compare = &MyCompare; In C, since arrays and pointers have a close equivalence, the following are the same: a = b[5]; a = *(b+5); a = *(5+b); a = 5[b]; Thus, pointers are often used in C as just another method to access arrays. To create dynamic data, the library functions Pascal doesn't have the same kind of pointers as C, but it does have an indirection operator that covers the most common use of C pointers. Each pointer is bound to a single dynamic data item, and can only be moved by assignment: type a = ^integer; var b, c: a; new(b); c := b; Pointers in Pascal are type safe; i.e. a pointer to one data type can only be assigned to a pointer of the same data type. Also pointers can never be assigned to non-pointer variables. Pointer arithmetic (a common source of programming errors in C, especially when combined with endianness issues and platform-independent type sizes) is not permitted in Pascal. All of these restrictions reduce the possibility of pointer-related errors in Pascal compared to C, but do not prevent invalid pointer references in Pascal altogether. For example, a runtime error will occur if a pointer is referenced before it has been initialized or after it has been disposed. Expressions{{unreferenced section|date=June 2013}}Precedence levelsThe languages differ significantly when it comes to expression evaluation, but all-in-all they are comparable. Pascal
TypingMost operators serve several purposes in Pascal, for instance, the minus sign may be used for negation, subtraction, or set difference (depending on both type and syntactical context), the Assignment and equality testsThe two languages use different operators for assignment. Pascal, like ALGOL, uses the mathematical equality operator It is a common mistake in C, due either to inexperience or to a simple typing error, to accidentally put assignment expressions in conditional statements such as This kind of mistake cannot happen in Pascal, as assignments are not expressions and do not have a value: using the wrong operator will cause an unambiguous compilation error, and it's also less likely that anyone would mistake the It is notable that ALGOL's conditional expression in the form Implementation issuesWhen Niklaus Wirth designed Pascal, the desire was to limit the number of levels of precedence (fewer parse routines, after all). So the OR and exclusive OR operators are treated just like an Addop and processed at the level of a math expression. Similarly, the AND is treated like a Mulop and processed with Term. The precedence levels are Level Syntax Element Operator 0 factor literal, variable 1 signed factor unary minus, NOT 2 term *, /, AND 3 expression +, -, OR Notice that there is only ONE set of syntax rules, applying to both kinds of operators. According to this grammar, then, expressions like x + (y AND NOT z) / 3 are perfectly legal. And, in fact, they are, as far as the parser is concerned. Pascal doesn't allow the mixing of arithmetic and Boolean variables, and things like this are caught at the semantic level, when it comes time to generate code for them, rather than at the syntax level. The authors of C took a diametrically opposite approach: they treat the operators as different, and in fact, in C there are no fewer than 15 levels. That's because C also has the operators '=', '+=' and its kin, '<<', '>>', '++', '--', etc. Although in C the arithmetic and Boolean operators are treated separately, the variables are not: a Boolean test can be made on any integer value. Logical connectivesIn Pascal a boolean expression that relies on a particular evaluation ordering (possibly via side-effects in function calls) is, more or less, regarded as an error. The Pascal compiler has the freedom to use whatever ordering it may prefer and must always evaluate the whole expression even if the result can be determined by partial evaluation. In C, dependence on boolean evaluation order is perfectly legal, and often systematically employed using the Short circuit expression evaluation has been commonly considered an advantage for C because of the "evaluation problem": var i: integer; a: packed array [1..10] of char; ... i := 1; while (i <= 10) and (a[i] <> 'x') do i := i+1; ... This seemingly straightforward search is problematic in Pascal because the array access a[i] would be invalid for i equal to 11. However, in superscalar processors there is a penalty for all jumps because they cause pipeline stalls, and programs created for them are more efficient if jumps are removed where possible. Pascal's ability to evaluate using a fixed formula without jumps can be an advantage with highly optimizing compilers, whereas C has effectively prevented this by requiring short circuit optimization. Control structuresStatements for building control structures are roughly analogous and relatively similar (at least the first three). Pascal has:
C has:
Pascal, in its original form, did not have an equivalent to default, but an equivalent else clause is a common extension. Pascal programmers otherwise had to guard case-statements with an expression such as: {{mono|if expr not in [A..B] then default-case}}. C has the so-called early-out statements break and continue, and some Pascals have them as well. Both C and Pascal have a goto statement. However, since Pascal has nested procedures/functions, jumps can be done from an inner procedure or function to the containing one; this was commonly used to implement error recovery. C has this ability via the ANSI C setjmp and longjmp. This is equivalent, but arguably less safe, since it stores program specific information like jump addresses and stack frames in a programmer accessible structure. Functions and proceduresPascal routines that return a value are called functions; routines that don't return a value are called procedures. All routines in C are called functions; C functions that do not return a value are declared with a return type of void. Pascal procedures are considered equivalent to C "void" functions, and Pascal functions are equivalent to C functions that return a value. The following two declarations in C: int f(int x, int y); void k(int q); are equivalent to the following declarations in Pascal: function f(x, y: integer): integer; procedure k(q: integer); Pascal has two different types of parameters: pass-by-value, and pass-by-reference (VAR). function f(var k: integer): integer; x := f(t); In C all parameters are passed by value but pass-by-reference can be simulated using pointers. The following segment is similar to the Pascal segment above: int f(int *k); //function accepts a pointer as parameter x = f(&t); C allows for functions to accept a variable number of parameters, known as variadic functions. int f(int a, ...); f(1, 2, 3, 4, 5); The function Additionally Pascal has I/O statements built into the language to handle variable amount of parameters, like C allows functions to be indirectly invoked through a function pointer. In the following example, the statement
int (*cmpar)(const char *a, const char *b); const char *s1 = "hello"; const char *s2 = "world"; cmpar = &strcmp; b = (*cmpar)(s1, s2); Pascal also allows functions and procedures to be passed as parameters to functions or procedures: procedure ShowHex(i: integer); ... end; procedure ShowInt(i: integer); ... end; procedure Demo(procedure Show(i: integer)); var j: integer; begin end; ... Demo(ShowHex); Demo(ShowInt); ... PreprocessorEarly C had neither constant declarations nor type declarations, and the C language was originally defined as needing a "preprocessor"; a separate program, and pass, that handled constant, include and macro definitions, to keep memory usage down. Later, with ANSI C, it obtained constant and type definitions features and the preprocessor also became part of the language itself, leading to the syntax we see today. Pascal constant and type defines are built in, but there were programmers using a preprocessor also with Pascal (sometimes the same one used with C), certainly not as common as with C. Although often pointed out as a "lack" in Pascal, technically C doesn't have program modularity nor macros built in either. It has a simple low level separate compilation facility, however (traditionally using the same generic linker used for assembly language), Pascal does not. Type escapesIn C, the programmer may inspect the byte-level representation of any object by pointing a int a; char *p = (char *)(&a); char c = *p; // first byte of a It may be possible to do something similar in Pascal using an undiscriminated variant record: var a: integer; b: real; a2c: record case boolean of false: (a: integer); true: (b: real); end; end; begin a2c.b := b; a := a2c.a; end; Although casting is possible on most Pascal compilers and interpreters, even in the code above a2c.a and a2c.b aren't required by any Pascal standardizations to share the same address space. Niklaus Wirth, the designer of Pascal, has written about the problematic nature of attempting type escapes using this approach: "Most implementors of Pascal decided that this checking would be too expensive, enlarging code and deteriorating program efficiency. As a consequence, the variant record became a favourite feature to breach the type system by all programmers in love with tricks, which usually turn into pitfalls and calamities". Several languages now specifically exclude such type escapes, for example Java, C# and Wirth's own Oberon. FilesIn C files do not exist as a built-in type (they are defined in a system header) and all I/O takes place via library calls. Pascal has file handling built into the language. The typical statements used to perform I/O in each language are: The main difference is that C uses a "format string" that is interpreted to find the arguments to the printf function and convert them, whereas Pascal performs that under the control of the language processor. The Pascal method is arguably faster, because no interpretation takes place, but the C method is highly extensible. Later Pascal implementations and extensionsSome popular Pascal implementations have incorporated virtually all C constructs into Pascal. Examples include type casts, being able to obtain the address of any variable, local or global, and different types of integers with special promotion properties. However, the incorporation of C's lenient attitude towards types and type conversions can result in a Pascal that loses some or all of its type security. For example, Java and C# were created in part to address some of the perceived type security issues of C, and have "managed" pointers that cannot be used to create invalid references. In its original form (as described by Niklaus Wirth), Pascal qualifies as a managed pointer language, some 30 years before either Java or C#. However, a Pascal amalgamated with C would lose that protection by definition. In general, the lower dependence on pointers for basic tasks makes it safer than C in practice. The Extended Pascal standard extends Pascal to support many things C supports, which the original standard Pascal did not, in a type safer manner. For example, schema types support (besides other uses) variable-length arrays while keeping the type-safety of mandatory carrying the array dimension with the array, allowing automatic run-time checks for out-of-range indices also for dynamically sized arrays. See also
Notes1. ^{{citation |last=Kamp |first=Poul-Henning |date=25 July 2011 |title=The Most Expensive One-byte Mistake |journal=ACM Queue |volume=9 |number=7 |issn=1542-7730 |accessdate=2 August 2011 |url=http://queue.acm.org/detail.cfm?id=2010365 }} Further reading
5 : Comparison of individual programming languages|C (programming language)|Pascal (programming language)|Pascal programming language family|Articles with example Pascal code |
随便看 |
|
开放百科全书收录14589846条英语、德语、日语等多语种百科知识,基本涵盖了大多数领域的百科知识,是一部内容自由、开放的电子版国际百科全书。