Sie sind auf Seite 1von 22

C (programming language)

From Wikipedia, the free encyclopedia

Jump to: navigation, search

C
Paradigm Appeared in Designed by Developer Typing discipline Major implementations imperative (procedural) 197 !ennis "itchie !ennis "itchie # $ell %a&s static, 'eak

()), *+,), $orland ), Watcom )

Influenced by

$ ($)-%,)-%), .%(/% 01,213 .ssem&ly, -%45, F/"6".7 a'k, csh, )88, )9, /&:ective;), $it),

Influenced

!, Java, Java+cript, %im&o, -erl, -<-, -ython

5n computing, C is a general;purpose, cross;platform, &lock structured, procedural, imperative computer programming language developed in 197 &y !ennis "itchie at the $ell 6elephone %a&oratories for use 'ith the =ni> operating system?2 3 .lthough ) 'as designed for implementing system soft'are,2@3 it is also 'idely used for developing application soft'are? 5t is 'idely used on a great many different soft'are platforms and computer architectures, and several popular compilers e>ist? ) has greatly influenced many other popular programming languages, most nota&ly )88, 'hich originally &egan as an e>tension to )?

Contents
1 -hilosophy )haracteristics

@ <istory @?1 Aarly developments @? B#" ) @?@ .7+5 ) and 5+/ ) @?C )99

C =ses D +ynta> 0 /perators 7 E<ello, 'orldE e>ample 1 !ata structures 1?1 -ointers 1? .rrays 1?@ .rray;pointer interchangea&ility

9 *emory management 1F %i&raries 11 *inimalism 11?1 .&sent features 11? =ndefined &ehavior

1 %anguage tools 1@ "elated languages 1C +ee also 1D Footnotes 10 "eferences 17 A>ternal links

[edit P!ilosop!y
) is an imperative (procedural) systems implementation language? 5t 'as designed to &e compiled using a relatively straightfor'ard compiler, to provide lo';level access to memory, to provide language constructs that map efficiently to machine instructions, and to reGuire minimal run;time support? ) 'as therefore useful for many applications that had formerly &een coded in assem&ly language? !espite its lo';level capa&ilities, the language 'as designed to encourage machine;independent programming? . standards;compliant and porta&ly 'ritten ) program can &e compiled for a very 'ide variety of computer platforms and operating systems 'ith little or no change to its source code? 6he language has &ecome availa&le on a very 'ide range of platforms, from em&edded microcontrollers to supercomputers?

[edit C!aracteristics

%ike most imperative languages in the .%(/% tradition, ) has facilities for structured programming and allo's le>ical varia&le scope and recursion, 'hile a static type system prevents many unintended operations? 5n ), all e>ecuta&le code is contained 'ithin functions? Function parameters are al'ays passed &y value? -ass;&y;reference is achieved in ) &y e>plicitly passing pointer values? <eterogeneous aggregate data types (struct) allo' related data elements to &e com&ined and manipulated as a unit? ) program source te>t is free;format, using the semicolon as a statement terminator (not a delimiter)? ) also e>hi&its the follo'ing more specific characteristics: non;nesta&le function definitions, although varia&les may &e hidden in nested &locks partially 'eak typingH for instance, characters can &e used as integers lo';level access to computer memory &y converting machine addresses to typed pointers function pointers allo'ing for a rudimentary form of closures and runtime polymorphism array inde>ing as a secondary notion, defined in terms of pointer arithmetic a preprocessor for macro definition, source code file inclusion, and conditional compilation comple> functionality such as 54/, string manipulation, and mathematical functions consistently delegated to li&rary routines around @F reserved key'ords synta> divergent from .%(/%, often follo'ing the lead of )Is predecessor $, for e>ample using { ... } rather than .%(/%Is begin ... end the eGual;sign for assignment (copying), much like Fortran t'o consecutive eGual;signs to test for eGuality (compare to .EQ. in Fortran or the eGual;sign in $.+5)) && and || in place of .%(/%Is and and or, 'hich are syntactically distinct from the &it;'ise operators & and | (used &y $ for &oth meanings) never evaluate the right operand if the result can &e determined from the left alone (short;circuit evaluation) a large num&er of compound operators, such as +=, ++, etc?

[edit "istory
[edit #arly developments
6he initial development of ) occurred at .6#6 $ell %a&s &et'een 1909 and 197@H according to "itchie, the most creative period occurred in 197 ? 5t 'as named E)E &ecause many of its features 'ere derived from an earlier language called E$E, 'hich according to Ben 6hompson 'as a stripped;do'n version of the $)-% programming language? 6he origin of ) is closely tied to the development of the =ni> operating system, originally implemented in assem&ly language on a -!-;7 &y "itchie and 6hompson, incorporating several ideas from colleagues? Aventually they decided to port the operating system to a -!-;11? $Is

lack of functionality to take advantage of some of the -!-;11Is features, nota&ly &yte addressa&ility, led to the development of an early version of the ) programming language? 6he original -!-;11 version of the =ni> system 'as developed in assem&ly language? $y 197@, 'ith the addition of struct types, the ) language had &ecome po'erful enough that most of the =ni> kernel 'as re'ritten in )? 6his 'as one of the first operating system kernels implemented in a language other than assem&ly? (Aarlier instances include the *ultics system ('ritten in -%45), and *)- (*aster )ontrol -rogram) for the $urroughs $DFFF 'ritten in .%(/% in 1901?)

[edit $%& C
5n 1971, $rian Bernighan and !ennis "itchie pu&lished the first edition of The C Programming Language? 6his &ook, kno'n to ) programmers as EB#"E, served for many years as an informal specification of the language? 6he version of ) that it descri&es is commonly referred to as EB#" )E? 6he second edition of the &ook covers the later .7+5 ) standard? B#" introduced several language features: standard 54/ li&rary
long int

data type data type

unsigned int

compound assignment operators =op 'ere changed to op= to remove the semantic am&iguity created &y the construct i=-10, 'hich had &een interpreted as i =- 10 instead of the possi&ly intended i = -10

Aven after the pu&lication of the 1919 ) standard, for many years B#" ) 'as still considered the Elo'est common denominatorE to 'hich ) programmers restricted themselves 'hen ma>imum porta&ility 'as desired, since many older compilers 'ere still in use, and &ecause carefully 'ritten B#" ) code can &e legal +tandard ) as 'ell? 5n early versions of ), only functions that returned a non;integer value needed to &e declared if used &efore the function definitionH a function used 'ithout any previous declaration 'as assumed to return an integer, if its value 'as used? For e>ample:
long int SomeFunction !" #$ int %t&erFunction !" $# #$ int $# 'allingFunction ! { long int test1" register #$ int $# test(" test1 = SomeFunction !" i) test1 * 0! test( = 0" else test( = %t&erFunction !" } return test("

.ll the a&ove commented;out int declarations could &e omitted in B#" )?

+ince B#" function declarations did not include any information a&out function arguments, function parameter type checks 'ere not performed, although some compilers 'ould issue a 'arning message if a local function 'as called 'ith the 'rong num&er of arguments, or if multiple calls to an e>ternal function used different num&ers or types of arguments? +eparate tools such as =ni>Is lint utility 'ere developed that (among other things) could check for consistency of function use across multiple source files? 5n the years follo'ing the pu&lication of B#" ), several unofficial features 'ere added to the language, supported &y compilers from .6#6 and some other vendors? 6hese included:
+oid

functions

functions returning struct or union types (rather than pointers) assignment for struct data types enumerated types

6he large num&er of e>tensions and lack of agreement on a standard li&rary, together 'ith the language popularity and the fact that not even the =ni> compilers precisely implemented the B#" specification, led to the necessity of standardiJation?

[edit A'(I C and I() C


Main article: ANSI C !uring the late 197Fs and 191Fs, versions of ) 'ere implemented for a 'ide variety of mainframe computers, minicomputers, and microcomputers, including the 5$* -), as its popularity &egan to increase significantly? 5n 191@, the .merican 7ational +tandards 5nstitute (.7+5) formed a committee, K@J11, to esta&lish a standard specification of )? 5n 1919, the standard 'as ratified as .7+5 K@?1D9;1919 E-rogramming %anguage )?E 6his version of the language is often referred to as .7+5 ), +tandard ), or sometimes )19? 5n 199F, the .7+5 ) standard ('ith formatting changes) 'as adopted &y the 5nternational /rganiJation for +tandardiJation (5+/) as 5+/45A) 9199:199F, 'hich is sometimes called )9F? 6herefore, the terms E)19E and E)9FE refer to the same programming language? .7+5, like other national standards &odies, no longer develops the ) standard independently, &ut defers to the 5+/ ) standard? 7ational adoption of updates to the international standard typically occurs 'ithin a year of 5+/ pu&lication? /ne of the aims of the ) standardiJation process 'as to produce a superset of B#" ), incorporating many of the unofficial features su&seGuently introduced? 6he standards committee also included several additional features such as function prototypes (&orro'ed from )88), +oid pointers, support for international character sets and locales, and preprocessor enhancements? 6he synta> for parameter declarations 'as also augmented to include the style used in )88, although the B#" interface continued to &e permitted, for compati&ility 'ith e>isting source code? )19 is supported &y current ) compilers, and most ) code &eing 'ritten no'adays is &ased on it? .ny program 'ritten only in +tandard ) and 'ithout any hard'are;dependent assumptions 'ill run correctly on any platform 'ith a conforming ) implementation, 'ithin its resource limits? Without such precautions, programs may compile only on a certain platform or 'ith a particular compiler, due, for e>ample, to the use of non;standard li&raries, such as (=5 li&raries, or to a

reliance on compiler; or platform;specific attri&utes such as the e>act siJe of data types and &yte endianness? 5n cases 'here code must &e compila&le &y either standard;conforming or B#" );&ased compilers, the ,,S-.',, macro can &e used to split the code into +tandard and B#" sections to take advantage of features availa&le only in +tandard )?

[edit C**
Main article: C99 .fter the .7+545+/ standardiJation process, the ) language specification remained relatively static for some time, 'hereas )88 continued to evolve, largely during its o'n standardiJation effort? 5n 199D 7ormative .mendment 1 to the 199F ) standard 'as pu&lished, to correct some details and to add more e>tensive support for international character sets? 6he ) standard 'as further revised in the late 199Fs, leading to the pu&lication of 5+/45A) 9199:1999 in 1999, 'hich is commonly referred to as E)99?E 5t has since &een amended three times &y 6echnical )orrigenda? 6he international ) standard is maintained &y the 'orking group 5+/45A) J6)14+) 4W(1C? )99 introduced several ne' features, including inline functions, several ne' data types (including long long int and a com/le0 type to represent comple> num&ers), varia&le;length arrays, support for variadic macros (macros of varia&le arity) and support for one;line comments &eginning 'ith ##, as in $)-% or )88? *any of these had already &een implemented as e>tensions in several ) compilers? )99 is for the most part &ack'ard compati&le 'ith )9F, &ut is stricter in some 'aysH in particular, a declaration that lacks a type specifier no longer has int implicitly assumed? . standard macro ,,S-.',1E2S3%4,, is defined 'ith value 1555016 to indicate that )99 support is availa&le? ()), +un +tudio and other ) compilers no' support many or all of the ne' features of )99? .s of FF7, 'ork has &egun in anticipation of another revision of the ) standard, informally called E)1xE? 6he ) standards committee has adopted guidelines to limit the adoption of ne' features that have not &een tested &y e>isting implementations?

[edit +ses
)Is primary use is for Esystem programmingE, including implementing operating systems and em&edded system applications, due to a com&ination of desira&le characteristics such as code porta&ility and efficiency, a&ility to access specific hard'are addresses, a&ility to EpunE types to match e>ternally imposed data access reGuirements, and lo' runtime demand on system resources? ) has also &een 'idely used to implement end;user applications, although as applications &ecame larger much of that development shifted to other, higher;level languages? /ne conseGuence of )Is 'ide acceptance and efficiency is that the compilers, li&raries, and interpreters of other higher;level languages are often implemented in )? ) is used as an intermediate language &y some implementations of higher;level languages, 'hich translate the input language to ) source code, perhaps along 'ith other o&:ect representations? 6he ) source code is compiled &y a ) compiler to produce o&:ect code? 6his approach may &e used to gain porta&ility () compilers e>ist for nearly all platforms) or for convenience (it avoids having to develop machine;specific code generators)? +ome programming languages 'hich use

) this 'ay are $it), Aiffel, Asterel, (am&it, the (lasgo' <askell )ompiler, %isp dialects, %ush, +ather, +Gueak, and ,ala? =nfortunately, ) 'as designed as a programming language, not as a compiler target language, and is thus less than ideal for use as an intermediate language? 6his has led to development of ); &ased intermediate languages such as );;?

[edit (ynta,
Main article: C syntax See also: C variable types an eclarations =nlike languages such as F/"6".7 77, ) source code is free;form 'hich allo's ar&itrary use of 'hitespace to format code, rather than column;&ased or te>t;line;&ased restrictions? )omments may appear either &et'een the delimiters #$ and $#, or (in )99) follo'ing ## until the end of the line? Aach source file contains declarations and function definitions? Function definitions, in turn, contain declarations and statements? !eclarations either define ne' types using key'ords such as struct, union, and enum, or assign types to and perhaps reserve storage for ne' varia&les, usually &y 'riting the type follo'ed &y the varia&le name? Bey'ords such as c&ar and int specify &uilt;in types? +ections of code are enclosed in &races ({ and }, sometimes called Ecurly &racketsE) to limit the scope of declarations and to act as a single statement for control structures? .s an imperative language, ) uses statements to specify actions? 6he most common statement is an expression statement, consisting of an e>pression to &e evaluated, follo'ed &y a semicolonH as a side effect of the evaluation, functions may &e called and varia&les may &e assigned ne' values? 6o modify the normal seGuential e>ecution of statements, ) provides several control; flo' statements identified &y reserved key'ords? +tructured programming is supported &y i)(; else) conditional e>ecution and &y do;7&ile, 7&ile, and )or iterative e>ecution (looping)? 6he )or statement has separate initialiJation, testing, and reinitialiJation e>pressions, any or all of 'hich can &e omitted? brea8 and continue can &e used to leave the innermost enclosing loop statement or skip to its reinitialiJation? 6here is also a non;structured goto statement 'hich &ranches directly to the designated la&el 'ithin the function? s7itc& selects a case to &e e>ecuted &ased on the value of an integer e>pression? A>pressions can use a variety of &uilt;in operators (see &elo') and may contain function calls? 6he order in 'hich operands to most operators, as 'ell as the arguments to functions, are evaluated is unspecifiedH the evaluations may even &e interleaved? <o'ever, all side effects (including storage to varia&les) 'ill occur &efore the ne>t EseGuence pointEH seGuence points include the end of each e>pression statement and the entry to and return from each function call? 6his permits a high degree of o&:ect code optimiJation &y the compiler, &ut reGuires ) programmers to e>ert more care to o&tain relia&le results than is needed for other programming languages? .lthough mimicked &y many languages &ecause of its 'idespread familiarity, )Is synta> has often &een criticiJed? For e>ample, Bernighan and "itchie say in the second edition of The C Programming Language, E), like any other language, has its &lemishes? +ome of the operators have the 'rong precedenceH some parts of the synta> could &e &etter?E +ome specific pro&lems 'orth noting are:

7ot checking num&er and types of arguments 'hen the function declaration has an empty parameter list? (6his provides &ack'ard compati&ility 'ith B#" ), 'hich lacked prototypes?) +ome Guestiona&le choices of operator precedence, as mentioned &y Bernighan and "itchie a&ove, such as == &inding more tightly than & and | in e>pressions like 0 & 1 == 0? 6he use of the = operator, used in mathematics for eGuality, to indicate assignment, follo'ing the precedent of Fortran, -%45, and $.+5), &ut unlike .%(/% and its derivatives? "itchie made this synta> design decision consciously, &ased primarily on the argument that assignment occurs more often than comparison? +imilarity of the assignment and eGuality operators (= and ==), making it easy to accidentally su&stitute one for the other? )Is 'eak type system permits each to &e used in the conte>t of the other 'ithout a compilation error (although some compilers produce 'arnings)? For e>ample, the conditional e>pression in i) a=b! is only true if a is not Jero after the assignment?2C3 . lack of infi> operators for comple> o&:ects, particularly for string operations, making programs 'hich rely heavily on these operations (implemented as functions instead) some'hat difficult to read? . declaration synta> that some find unintuitive, particularly for function pointers? ("itchieIs idea 'as to declare identifiers in conte>ts resem&ling their use: Edeclaration reflects useE?)

[edit )perators
Main article: !perators in C an C"" ) supports a rich set of operators, 'hich are sym&ols used 'ithin an e>pression to specify the manipulations to &e performed 'hile evaluating that e>pression? ) has operators for: arithmetic eGuality testing order relations &oolean logic &it'ise logic assignment increment and decrement reference and dereference conditional evaluation mem&er selection type conversion o&:ect siJe function argument collection seGuencing

su&e>pression grouping

) has a formal grammar, specified &y the ) standard?

[edit -"ello. /orld- e,ample


6he Ehello, 'orldE e>ample 'hich appeared in the first edition of B#" has &ecome the model for an introductory program in most programming te>t&ooks, regardless of programming language? 6he program prints Ehello, 'orldE to the standard output, 'hich is usually a terminal or screen display? . standard;conforming Ehello, 'orldE program is:2D3
9include :stdio.&* int main +oid! { /rint) ;&ello< 7orld=n;!" return 0" }

6he first line of the program contains a preprocessing directive, indicated &y 9include? 6his causes the preprocessor L the first tool to e>amine source code as it is compiled L to su&stitute the line 'ith the entire te>t of the stdio.& standard header, 'hich contains declarations for standard input and output functions such as /rint)? 6he angle &rackets surrounding stdio.& indicate that stdio.& is located using a search strategy that prefers standard headers to other headers having the same name? !ou&le Guotes may also &e used to include local or pro:ect; specific header files? 6he ne>t line indicates that a function named main is &eing defined? 6he main function serves a special purpose in ) programs: 6he run;time environment calls the main function to &egin program e>ecution? 6he type specifier int indicates that the return value# the value that is returned to the invoker (in this case the run;time environment) as a result of evaluating the main function, is an integer? 6he key'ord +oid as a parameter list indicates that the main function takes no arguments?203 6he opening curly &race indicates the &eginning of the definition of the main function? 6he ne>t line calls (e>ecutes the code for) a function named /rint), 'hich 'as declared in stdio.& and is supplied from a system li&rary? 5n this call, the /rint) function is passe (provided 'ith) a single argument, the address of the first character in the string literal ;&ello< 7orld=n;? 6he string literal is an unnamed array 'ith elements of type c&ar, set up automatically &y the compiler 'ith a final F;valued character to mark the end of the array (/rint) needs to kno' this)? 6he =n is an escape se$uence that ) translates to a ne%line character, 'hich on output signifies the end of the current line? 6he return value of the /rint) function is of type int, &ut it is silently discarded since it is not used? (. more careful program might test the return value to determine 'hether or not the /rint) function succeeded?) 6he semicolon " terminates the statement? 6he return statement terminates the e>ecution of the main function and causes it to return the integer value F, 'hich is interpreted &y the run;time system as an e>it code indicating successful e>ecution? 6he closing curly &race indicates the end of the code for the main function?

[edit Data structures

) has a static 'eak typing type system that shares some similarities 'ith that of other .%(/% descendants such as -ascal? 6here are &uilt;in types for integers of various siJes, &oth signed and unsigned, floating;point num&ers, characters, and enumerated types (enum)? )99 added a &oolean datatype? 6here are also derived types including arrays, pointers, records (struct), and untagged unions (union)? ) is often used in lo';level systems programming 'here escapes from the type system may &e necessary? 6he compiler attempts to ensure type correctness of most e>pressions, &ut the programmer can override the checks in various 'ays, either &y using a type cast to e>plicitly convert a value from one type to another, or &y using pointers or unions to reinterpret the underlying &its of a value in some other 'ay? [edit Pointers ) supports the use of pointers, a very simple type of reference that records, in effect, the address or location of an o&:ect or function in memory? -ointers can &e ere&erence to access data stored at the address pointed to, or to invoke a pointed;to function? -ointers can &e manipulated using assignment and also pointer arithmetic? 6he run;time representation of a pointer value is typically a ra' memory address (perhaps augmented &y an offset;'ithin;'ord field), &ut since a pointerIs type includes the type of the thing pointed to, e>pressions including pointers can &e type;checked at compile time? -ointer arithmetic is automatically scaled &y the siJe of the pointed;to data type? (+ee .rray;pointer interchangea&ility &elo'?) -ointers are used for many different purposes in )? 6e>t strings are commonly manipulated using pointers into arrays of characters? !ynamic memory allocation, 'hich is descri&ed &elo', is performed using pointers? *any data types, such as trees, are commonly implemented as dynamically allocated struct o&:ects linked together using pointers? -ointers to functions are useful for call&acks from event handlers? . null pointer is a pointer value that points to no valid location (it is often represented &y address Jero)? !ereferencing a null pointer is therefore meaningless, typically resulting in a run;time error? 7ull pointers are useful for indicating special cases such as no next pointer in the final node of a linked list, or as an error indication from functions returning pointers? ,oid pointers (+oid $) point to o&:ects of unkno'n type, and can therefore &e used as EgenericE data pointers? +ince the siJe and type of the pointed;to o&:ect is not kno'n, void pointers cannot &e dereferenced, nor is pointer arithmetic on them allo'ed, although they can easily &e (and in many conte>ts implicitly are) converted to and from any other o&:ect pointer type? )areless use of pointers is potentially dangerous? $ecause they are typically unchecked, a pointer varia&le can &e made to point to any ar&itrary location, 'hich can cause undesira&le effects? .lthough properly;used pointers point to safe places, they can &e made to point to unsafe places &y using invalid pointer arithmeticH the o&:ects they point to may &e deallocated and reused (dangling pointers)H they may &e used 'ithout having &een initialiJed ('ild pointers)H or they may &e directly assigned an unsafe value using a cast, union, or through another corrupt pointer? 5n general, ) is permissive in allo'ing manipulation of and conversion &et'een pointer types, although compilers typically provide options for various levels of checking? +ome other programming languages address these pro&lems &y using more restrictive reference types? [edit Arrays .rray types in ) are al'ays one;dimensional and, traditionally, of a fi>ed, static siJe specified at compile time? (6he more recent )99 standard also allo's a form of varia&le;length arrays?) <o'ever, it is also possi&le to allocate a &lock of memory (of ar&itrary siJe) at run;time, using

the standard li&raryIs malloc function, and treat it as an array? )Is unification of arrays and pointers (see &elo') means that true arrays and these dynamically;allocated, simulated arrays are virtually interchangea&le? +ince arrays are al'ays accessed (in effect) via pointers, array accesses are typically not checked against the underlying array siJe, although the compiler may provide &ounds checking as an option? .rray &ounds violations are therefore possi&le and rather common in carelessly 'ritten code, and can lead to various repercussions, including illegal memory accesses, corruption of data, &uffer overruns, and run;time e>ceptions? ) does not have a special provision for declaring multidimensional arrays, &ut rather relies on recursion 'ithin the type system to declare arrays of arrays, 'hich effectively accomplishes the same thing? 6he inde> values of the resulting Emultidimensional arrayE can &e thought of as increasing in ro';ma:or order? .lthough ) supports static arrays, it is not reGuired that array indices &e validated (&ounds checking)? For e>ample, one can try to 'rite to the si>th element of an array 'ith five elements, generally yielding undesira&le results? 6his type of &ug, called a bu&&er over&lo% or bu&&er overrun# is notorious for causing a num&er of security pro&lems? /n the other hand, since &ounds checking elimination technology 'as largely none>istent 'hen ) 'as defined, &ounds checking came 'ith a severe performance penalty, particularly in numerical computation? . fe' years earlier, some Fortran compilers had a s'itch to toggle &ounds checking on or offH ho'ever, this 'ould have &een much less useful for ), 'here array arguments are passed as simple pointers? *ultidimensional arrays are commonly used in numerical algorithms (mainly from applied linear alge&ra) to store matrices? 6he structure of the ) array is 'ell suited to this particular task? <o'ever, since arrays are passed merely as pointers, the &ounds of the array must &e kno'n fi>ed values or else e>plicitly passed to any su&routine that reGuires them, and dynamically siJed arrays of arrays cannot &e accessed using dou&le inde>ing? (. 'orkaround for this is to allocate the array 'ith an additional Ero' vectorE of pointers to the columns?) )99 introduced Evaria&le;length arraysE 'hich address some, &ut not all, of the issues 'ith ordinary ) arrays? See also: C string [edit Array0pointer interc!angeability . distinctive (&ut potentially confusing) feature of ) is its treatment of arrays and pointers? 6he array;su&script notation 0>i? can also &e used 'hen 0 is a pointerH the interpretation (using pointer arithmetic) is to access the i+1!th of several ad:acent data o&:ects pointed to &y 0, counting the o&:ect that 0 points to ('hich is 0>0?) as the first element of the array? Formally, 0>i? is eGuivalent to $ 0 + i!? +ince the type of the pointer involved is kno'n to the compiler at compile time, the address that 0 + i points to is not the address pointed to &y 0 incremented &y i &ytes, &ut rather incremented &y i multiplied &y the siJe of an element that 0 points to? 6he siJe of these elements can &e determined 'ith the operator si@eo) &y applying it to any dereferenced element of 0, as in n = si@eo) $0 or n = si@eo) 0>0?? Furthermore, in most e>pression conte>ts (a nota&le e>ception is si@eo) array), the name of an array is automatically converted to a pointer to the arrayIs first elementH this implies that an array is never copied as a 'hole 'hen named as an argument to a function, &ut rather only the address of its first element is passed? 6herefore, although )Is function calls use pass;&y;value semantics, arrays are in e&&ect passed &y reference? 6he num&er of elements in a declared array a can &e determined as si@eo) a # si@eo) a>0??

.n interesting demonstration of the interchangea&ility of pointers and arrays is sho'n &elo'? 6he four assignments are eGuivalent and each is valid ) code? 7ote ho' the last line contains the strange code i>0? = 1", 'hich has the inde> varia&le i apparently interchanged 'ith the array varia&le 0? 6his last line might &e found in o&fuscated ) code?
#$ 0 designates an arraA $# 0>i? = 1" $ 0 + i! = 1" $ i + 0! = 1" i>0? = 1" #$ strange< but correctB i>0? is eCui+alent to $ i + 0! $#

<o'ever, there is a distinction to &e made &et'een arrays and pointer varia&les? Aven though the name of an array is in most e>pression conte>ts converted to a pointer (to its first element), this pointer does not itself occupy any storage? )onseGuently, you cannot change 'hat an array Epoints toE, and it is impossi&le to assign to an array? (.rrays may ho'ever &e copied using the memc/A function, for e>ample?)

[edit Memory management


/ne of the most important functions of a programming language is to provide facilities for managing memory and the o&:ects that are stored in memory? ) provides three distinct 'ays to allocate memory for o&:ects: +tatic memory allocation: space for the o&:ect is provided in the &inary at compile;timeH these o&:ects have an e>tent (or lifetime) as long as the &inary 'hich contains them is loaded into memory .utomatic memory allocation: temporary o&:ects can &e stored on the stack, and this space is automatically freed and reusa&le after the &lock in 'hich they are declared is e>ited !ynamic memory allocation: &locks of memory of ar&itrary siJe can &e reGuested at run; time using li&rary functions such as malloc from a region of memory called the heapH these &locks persist until su&seGuently freed for reuse &y calling the li&rary function )ree

6hese three approaches are appropriate in different situations and have various tradeoffs? For e>ample, static memory allocation has no allocation overhead, automatic allocation may involve a small amount of overhead, and dynamic memory allocation can potentially have a great deal of overhead for &oth allocation and deallocation? /n the other hand, stack space is typically much more limited and transient than either static memory or heap space, and dynamic memory allocation allo's allocation of o&:ects 'hose siJe is kno'n only at run;time? *ost ) programs make e>tensive use of all three? Where possi&le, automatic or static allocation is usually preferred &ecause the storage is managed &y the compiler, freeing the programmer of the potentially error;prone chore of manually allocating and releasing storage? <o'ever, many data structures can gro' in siJe at runtime, and since static allocations (and automatic allocations in )19 and )9F) must have a fi>ed siJe at compile;time, there are many situations in 'hich dynamic allocation must &e used? -rior to the )99 standard, varia&le;siJed arrays 'ere a common e>ample of this (see EmallocE for an e>ample of dynamically allocated arrays)? .utomatically and dynamically allocated o&:ects are only initialiJed if an initialiJed is e>plicitly specifiedH other'ise they initially have indeterminate values (typically, 'hatever &it pattern happens to &e present in the storage, 'hich might not even represent a valid value for that type)?

5f the program attempts to access an uninitialiJed value, the results are undefined? *any modern compilers try to detect and 'arn a&out this pro&lem, &ut &oth false positives and false negatives occur? .nother issue is that heap memory allocation has to &e manually synchroniJed 'ith its actual usage in any program in order for it to &e reused as much as possi&le? For e>ample, if the only pointer to a heap memory allocation goes out of scope or has its value over'ritten &efore )ree ! has &een called, then that memory cannot &e recovered for later reuse and is essentially lost to the program, a phenomenon kno'n as a memory lea'( )onversely, it is possi&le to release memory too soon and continue to access itH ho'ever, since the allocation system can re;allocate or itself use the freed memory, unpredicta&le &ehavior is likely to occur 'hen the multiple users corrupt each otherIs data? 6ypically, the symptoms 'ill appear in a portion of the program far removed from the actual error? +uch issues are ameliorated in languages 'ith automatic gar&age collection or ".55?

[edit 1ibraries
6he ) programming language uses li&raries as its primary method of e>tension? 5n ), a li&rary is a set of functions contained 'ithin a single EarchiveE file? Aach li&rary typically has a header file, 'hich contains the prototypes of the functions contained 'ithin the li&rary that may &e used &y a program, and declarations of special data types and macro sym&ols used 'ith these functions? 5n order for a program to use a li&rary, it must include the li&raryIs header file, and the li&rary must &e linked 'ith the program, 'hich in many cases reGuires compiler flags (e?g?, -lm, shorthand for Emath li&raryE)? 6he most common ) li&rary is the ) standard li&rary, 'hich is specified &y the 5+/ and .7+5 ) standards and comes 'ith every ) implementation? (EFreestandingE 2em&edded3 ) implementations may provide only a su&set of the standard li&rary?) 6his li&rary supports stream input and output, memory allocation, mathematics, character strings, and time values? .nother common set of ) li&rary functions are those used &y applications specifically targeted for =ni> and =ni>;like systems, especially functions 'hich provide an interface to the kernel? 6hese functions are detailed in various standards such as -/+5K and the +ingle =75K +pecification? +ince many programs have &een 'ritten in ), there are a 'ide variety of other li&raries availa&le? %i&raries are often 'ritten in ) &ecause ) compilers generate efficient o&:ect codeH programmers then create interfaces to the li&rary so that the routines can &e used from higher;level languages like Java, -erl, and -ython?

[edit Minimalism
)Is design is tied to its intended use as a systems implementation language? )onseGuently, it does not reGuire run;time checks for conditions that 'ould never occur in correct programs, it provides simple, direct access to any addressa&le o&:ect (for e>ample, memory;mapped device control registers), and its source;code e>pressions can &e translated in a straightfor'ard manner to primitive machine operations in the e>ecuta&le code? +ome early ) compilers 'ere comforta&ly implemented (as a fe' distinct passes communicating via intermediate files) on -!-;11 processors having only 10 address &itsH ho'ever, )99 assumes a D1 B$ minimum compilation platform? . popular saying, repeated &y such nota&le language designers as $:arne +troustrup, is that E) makes it easy to shoot yourself in the foot?E273 5n other 'ords, ) permits some operations that are

sometimes not desira&le, and thus many simple programming errors are not detected &y the compiler and may not &e readily apparent at runtime? 5f sufficient care and discipline are not used in programming and maintenance, this may lead to programs 'ith unpredicta&le &ehavior and security holes? (.lthough this is not uniGue to ), ) provides less protection than do many other programming languages?) With time, e>ternal tools 'ere developed to perform e>tra compile; and run;time checking? 7othing prevents a compiler from providing checks not reGuired &y the language definition, although for some systems programming applications the performance cost of additional run; time checking may &e deemed unaccepta&le? 5n their response to criticism of ) not &eing a strongly;typed programming language, Bernighan and "itchie made reference to the &asic design philosophy of ): E7evertheless, ) retains the &asic philosophy that programmers kno' 'hat they are doingH it only reGuires that they state their intentions e>plicitly?E213293

[edit Absent features


6he relatively lo';level nature of the language affords the programmer close control over 'hat the computer does, 'hile allo'ing specially tailoring and aggressive optimiJation for a particular platform? 6his allo's the code to run efficiently on very limited hard'are, such as em&edded systems? ) does not have some features that are availa&le in some other programming languages: 7o assignment of arrays or strings (copying can &e done via standard functionsH assignment of o&:ects having struct or union type is supported) 7o automatic gar&age collection 7o reGuirement for &ounds checking of arrays 7o operations on 'hole arrays 7o synta> for ranges, such as the D..E notation used in several languages 7o separate $oolean type: Jero4nonJero is used instead21F3 7o nested function definitions 7o formal closures or functions as parameters (only function and varia&le pointers) 7o generators or coroutinesH intra;thread control flo' consists of nested function calls, e>cept for the use of the long:mp or setconte>t li&rary functions 7o e>ception handlingH standard li&rary functions signify error conditions 'ith the glo&al errno varia&le and4or special return values /nly rudimentary support for modular programming 7o compile;time polymorphism in the form of function or operator overloading /nly rudimentary support for generic programming ,ery limited support for o&:ect;oriented programming 'ith regard to polymorphism and inheritance %imited support for encapsulation 7o native support for multithreading and net'orking

7o standard li&raries for computer graphics and several other application programming needs

. num&er of these features are availa&le as e>tensions in some compilers, or can &e supplied &y third;party li&raries, or can &e simulated &y adopting certain coding disciplines?

[edit +ndefined be!avior


*any operations in ) that have undefined &ehavior are not reGuired to &e diagnosed at compile time? 5n the case of ), Eundefined &ehaviorE means that the e>act &ehavior 'hich arises is not specified &y the standard, and e>actly 'hat 'ill happen does not have to &e documented &y the ) implementation? . famous, although misleading, e>pression in the ne'sgroups comp?std?c and comp?lang?c is that the program could cause Edemons to fly out of your noseE?2113 +ometimes in practice 'hat happens for an instance of undefined &ehavior is a &ug that is hard to track do'n and 'hich may corrupt the contents of memory? +ometimes a particular compiler generates 'ell; &ehaved actions that are not the same as 'ould &e o&tained using a different ) compiler? 6he reason some &ehavior has &een left undefined is to allo' compilers for a 'ide variety of instruction set architectures to generate more efficient e>ecuta&le code for 'ell;defined &ehavior, 'hich 'as deemed important for )Is primary role as a systems implementation languageH thus ) makes it the programmerIs responsi&ility to avoid undefined &ehavior? A>amples of undefined &ehavior are: accessing outside the &ounds of an array overflo'ing a signed integer reaching the end of a function 'ithout finding a return statement, 'hen the return value is used reading the value of a varia&le &efore initialiJing it

6hese operations are all programming errors that could occur using many programming languagesH ) dra's criticism &ecause its standard e>plicitly identifies numerous cases of undefined &ehavior, including some 'here the &ehavior could have &een made 'ell defined, and does not specify any run;time error handling mechanism? 5nvoking ))lus& ! on a stream opened for input is an e>ample of a different kind of undefined &ehavior, not necessarily a programming error &ut a case for 'hich some conforming implementations may provide 'ell;defined, useful semantics (in this e>ample, presuma&ly discarding input through the ne>t ne';line) as an allo'ed extension? =se of such nonstandard e>tensions generally limits soft'are porta&ility?

[edit 1anguage tools


6ools have &een created to help ) programmers avoid some of the pro&lems inherent in the language, such as statements 'ith undefined &ehavior or statements that are not a good practice &ecause they are more likely to result in unintended &ehavior or run;time errors? .utomated source code checking and auditing are &eneficial in any language, and for ) many such tools e>ist, such as %int? . common practice is to use %int to detect Guestiona&le code 'hen a program is first 'ritten? /nce a program passes %int, it is then compiled using the ) compiler? .lso, many compilers can optionally 'arn a&out syntactically valid constructs that are likely to actually &e errors? *5+". ) is a proprietary set of guidelines to avoid such Guestiona&le code, developed for em&edded systems?

6here are also compilers, li&raries and operating system level mechanisms for performing array &ounds checking, &uffer overflo' detection, serialiJation and automatic gar&age collection, that are not a standard part of )? 6ools such as -urify, ,algrind, and linking 'ith li&raries containing special versions of the memory allocation functions can help uncover runtime memory errors? )proto is a program that 'ill read a ) source file and output prototypes of all the functions 'ithin the source file? 6his program can &e used in con:unction 'ith the make command to create ne' files containing prototypes each time the source file has &een changed? 6hese prototype files can &e included &y the original source file (e?g?, as Efilename?pE), 'hich reduces the pro&lems of keeping function definitions and source files in agreement?

[edit &elated languages


) has directly or indirectly influenced many later languages such as Java, )9, -erl, -<-, Java+cript, %-), and =ni>Is csh and rc shells? 6he most pervasive influence has &een syntactical: all of the languages mentioned com&ine the statement and (more or less recogniJa&ly) e>pression synta> of ) 'ith type systems, data models and4or large;scale program structures that differ from those of ), sometimes radically? When o&:ect;oriented languages &ecame popular, )88 and /&:ective;) 'ere t'o different e>tensions of ) that provided o&:ect;oriented capa&ilities? $oth languages 'ere originally implemented as preprocessors ;; source code 'as translated into ), and then compiled 'ith a ) compiler? $:arne +troustrup devised the )88 programming language as one approach to providing o&:ect; oriented functionality 'ith );like synta>? )88 adds greater typing strength, scoping and other tools useful in o&:ect;oriented programming and permits generic programming via templates? 7early a superset of ), )88 no' supports most of ), 'ith a fe' e>ceptions (see )ompati&ility of ) and )88 for an e>haustive list of differences)? =nlike )88, 'hich maintains nearly complete &ack'ards compati&ility 'ith ), the ! language makes a clean &reak 'ith ) 'hile maintaining the same general synta>? 5t a&andons a num&er of features of ) 'hich Walter $right (the designer of !) considered undesira&le, including the ) preprocessor and trigraphs? +ome, &ut not all, of !Is e>tensions to ) overlap 'ith those of )88? /&:ective;) 'as originally a very EthinE layer on top of, and remains a strict superset of, ) that permits o&:ect;oriented programming using a hy&rid dynamic4static typing paradigm? /&:ective; ) derives its synta> from &oth ) and +malltalk: synta> that involves preprocessing, e>pressions, function declarations and function calls is inherited from ), 'hile the synta> for o&:ect;oriented features 'as originally taken from +malltalk? %im&o is a language developed &y the same team at $ell %a&s that 'as responsi&le for ) and =ni>, and 'hile retaining some of the synta> and the general style, introduced gar&age collection, )+- &ased concurrency and other ma:or innovations?2citation nee e 3

[edit (ee also


)omparison of programming languages 5nternational /&fuscated ) )ode )ontest %ist of articles 'ith ) programs %ist of compilers

)omparison of -ascal and )

[edit 2ootnotes
1? 3 !ennis *? "itchie (Jan 199@)? E6he !evelopment of the ) %anguageE? "etrieved on Jan 1,
FF1? E6he scheme of type composition adopted &y ) o'es considera&le de&t to .lgol 01, although it did not, perhaps, emerge in a form that .lgolIs adherents 'ould approve of?E

? 3 +te'art, $ill ( FFF;F1;F7)? E<istory of the ) -rogramming %anguageE? Living Internet?


"etrieved on FF0;1F;@1?

@? 3 -atricia B? %a'lis, c?:? kemp systems, inc? (1997)? E(uidelines for )hoosing a )omputer
%anguage: +upport for the ,isionary /rganiJationE? .da 5nformation )learinghouse? "etrieved on FF0;F7;11?

C? 3 http:44'''?cs?ucr?edu4Mn>iao4cs1F4errors?htm 1F )ommon -rogramming *istakes in ) D? 3 6he original e>ample code 'ill compile on most modern compilers that are not in strict
standard compliance mode, &ut it does not fully conform to the reGuirements of either )19 or )99? 5n fact, )99 reGuires that a diagnostic message &e produced?

0? 3 6he main function actually has t'o arguments, int argc and c&ar $arg+>?, respectively,

'hich can &e used to handle command line arguments? 6he ) standard reGuires that &oth forms of main &e supported, 'hich is special treatment not afforded any other function?

7? 3 http:44'''?research?att?com4M&s4&sNfaG?html9really;say;that +troustrup: F.O 1? 3 !ennis "itchie? E6he !evelopment of the ) %anguageE? "etrieved on FF0;F7; 0? 9? 3 $rian W? Bernighan and !ennis *? "itchie: The C Programming Language#
<all, 1911, p? @?
nd

ed?, -rentice

1F? 3 6he 1999 revision of the ) standard added a type ,Eool, &ut it 'as not retrofit into the
languageIs e>isting $oolean conte>ts?

11? 3 EJargon File entry for nasal emonsE?

[edit &eferences

$rian Bernighan, !ennis "itchie: The C Programming Language? .lso kno'n as B#" L 6he original &ook on )?

1st, -rentice <all 1971H 5+$7 F;1@;11F10@;@? -re;.7+5 )?


nd, -rentice <all 1911H 5+$7 F;1@;11F@0 ;1? .7+5 )? 5+/45A) 9199? /fficial )99 documents, including technical corrigenda and a rationale? .s of FF7 the latest version of the standard is 5+/45A) 9199:6)@-!F (@?01 *i$)? +amuel -? <ar&ison, (uy %? +teele: C: A )e&erence Manual? 6his &ook is e>cellent as a definitive reference manual, and for those 'orking on ) compilers? 6he &ook contains a $7F grammar for )?

Dth, -rentice <all FF H 5+$7 F;1@;F19D9 ;K?


!erek *? Jones: The Ne% C Stan ar : A Cultural an *conomic Commentary, .ddison;Wesley, 5+$7 F; F1;7F917;1, online material "o&ert +edge'ick: Algorithms in C, .ddison;Wesley, 5+$7 F; F1;@1CD ;D (-art 1PC) and 5+$7 F; F1;@100@;@ (-art D) William <? -ress, +aul .? 6eukolsky, William 6? ,etterling, $rian -? Flannery: 7umerical "ecipes in ) (6he .rt of +cientific )omputing), 5+$7 F;D 1;C@1F1;D

[edit #,ternal lin4s


Wiki&ooks has a &ook on the topic of C Programming .t Wikiversity, you can learn a&out: Topic:C 6he current +tandard ()99 'ith 6echnical corrigenda 6)1, 6) , and 6)@ included)-!F (@?01 *i$) 5+/ ) Working (roup (official We& site) The +evelopment o& the C Language &y !ennis *? "itchie comp?lang?c FreGuently .sked Ouestions 6he ) $ook &y *?$anahan;!?$rady;*?!oran (.ddison;Wesley, nd ed?) L &ook for &eginning and intermediate students, no' out of print and free to do'nload? The Ne% C Stan ar : An economic an cultural commentary-!F (1F?F *i$) L .n unpu&lished &ook a&out Edetailed analysis of the 5nternational +tandard for the ) language?E

v5d5e

C programming language
1ibraries 1anguage 2eatures Descendants C and )t!er 1anguages ) standard li&rary 6 gli&c 6 !ietli&c 6 u)li&c 6 7e'li& +tring 6 +ynta> 6 -reprocessor 6 ,aria&le types and declarations 6 Functions )88 6 /&:ective;) 6 ! 6 )9 6 )yclone 6 Java

)ompati&ility of ) and )88 6 /perators in ) and )88 6 )omparison of -ascal and ) 6 ) to Java &yte;code compiler "etrieved from Ehttp:44en?'ikipedia?org4'iki4)N(programmingNlanguage)E )ategories: ) programming language Q )urly &racket programming languages Q -rocedural programming languages <idden categories: .ll articles 'ith unsourced statements Q .rticles 'ith unsourced statements since +eptem&er FF1
7ie/s

.rticle !iscussion #dit t!is page <istory

Personal tools

1og in 8 create account

'avigation


(earc!

*ain page )ontents Featured content )urrent events "andom article


Top of Form

Go

Search
Bottom of Form

Interaction


Toolbo,

.&out Wikipedia )ommunity portal "ecent changes )ontact Wikipedia !onate to Wikipedia <elp What links here "elated changes =pload file +pecial pages -rinta&le version -ermanent link )ite this page .frikaans .lemannisch RSTUVWX .ragonYs .sturianu .JZr&aycan $[n;l[m;g\ ]^_`abcd`e ]^_`abcd`e (f`a`gd^hij`)

1anguages

$osanski $reJhoneg ]k_l`acdm )ataln oesky )orsu )ymraeg !ansk !eutsch Aesti pqqrstuv Aspawol Asperanto Auskara Franxais (aeilge (alego <rvatski $ahasa 5ndonesia 5nterlingua yslenska 5taliano z{|}~ Burd 4 %atina %atvieu %ietuvi *agyar `d^cdm $ahasa *elayu *ng;dng;ng l_

7ederlands 7orsk (&okml) 7orsk (nynorsk) -olski -ortugus "om[n bccdm +hGip +imple Anglish +lovenina +lovenina acdm 4 +rpski +rpskohrvatski 4 acdah`fcdm +uomi +venska 6aG&aylit 6ing ,it 6rkxe da`cd` {{ { emait ka

6his page 'as last modified on

+eptem&er FF1, at F0:D0?

.ll te>t is availa&le under the terms of the (7= Free !ocumentation %icense? (+ee Copyrig!ts for details?)

Wikipedia is a registered trademark of the Wikimedia Foundation, 5nc?, a =?+? registered DF1(c)(@) ta>;deducti&le nonprofit charity? -rivacy policy .&out Wikipedia !isclaimers

Das könnte Ihnen auch gefallen