C Programming Language
C Programming Language
C
Paradigm Appeared in Designed by Developer Typing discipline Major implementations imperative (procedural) 197 !ennis "itchie !ennis "itchie # $ell %a&s static, 'eak
Influenced by
$ ($)-%,)-%), .%(/% 01,213 .ssem&ly, -%45, F/"6".7 a'k, csh, )88, )9, /&:ective;), $it),
Influenced
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 ⁢'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
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?
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≤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
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?
) 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≤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≤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?)
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≤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
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?
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?
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 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 -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?
[edit &eferences
$rian Bernighan, !ennis "itchie: The C Programming Language? .lso kno'n as B#" L 6he original &ook on )?
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
Personal tools
'avigation
(earc!
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
.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