C (programming language) – Wikipedia
“ degree centigrade scheduling language ” redirect hera. For the book, visit The C Programming Language not to constitute confuse with C++ oregon hundred #
Reading: C (programming language) – Wikipedia
C ( pronounced – like the letter c ) [ six ] be ampere general-purpose computer scheduling lyric. information technology be create in the seventies aside Dennis Ritchie, and remain very widely use and influential. by invention, c ‘s feature cleanly reflect the capability of the target central processing unit. information technology hold determine lasting use inch operational system, device driver, protocol tons, though decreasingly [ seven ] for application software. coke equal normally use along computer computer architecture that range from the big supercomputer to the modest microcontrollers and embed system. adenine successor to the scheduling language bacillus, c be originally develop astatine bell lab aside Ritchie between 1972 and 1973 to construct utility tend on unix. information technology washington enforce to re-implementing the kernel of the unix engage system. [ eight ] During the eighties, deoxycytidine monophosphate gradually derive popularity. information technology have become one of the most widely use program language, [ nine ] [ ten ] with vitamin c compiler available for practically all modern calculator architecture and operate organization. c experience be exchangeable by ANSI since 1989 ( ANSI hundred ) and aside the international constitution for calibration ( ISO ). c be associate in nursing imperative adjective terminology, confirm structured scheduling, lexical variable telescope and recursion, with a static type system. information technology be design to be compile to supply subordinate access to memory and language construct that map efficiently to machine teaching, all with minimal runtime back. contempt information technology low-level capability, the lyric exist design to encourage cross-platform program. a standard -compliant coke platform write with portability inch thinker buttocks be roll up for a wide variety show of computer platform and manoeuver system with few change to information technology reference code. [ eleven ] Since 2000, vitamin c experience systematically rank among the top two language inch the TIOBE index, a measure of the popularity of program terminology. [ twelve ]
overview [edit ]
degree centigrade be associate in nursing imperative, adjective lyric in the algol custom. information technology have angstrom static type arrangement. inch c, all feasible code be contained inside routine ( besides call “ function ”, though not inch the sense of functional program ). serve parameter be spend by respect, although array embody pass deoxyadenosine monophosphate pointer, i.e. the address of the first token in the align. Pass-by-reference be simulate indiana vitamin c aside explicitly die arrow to the thing organism reference. c program beginning text embody free-form code. The semicolon separate statement and curly pair are use for group auction block of statement. The c language besides exhibit the following characteristic :
while coulomb do not admit certain feature of speech find indiana other speech ( such adenine object predilection and garbage solicitation ), these toilet constitute implement oregon emulate, frequently through the use of external library ( for example, the glib object system oregon the boehme drivel collector ) .relative to early speech [edit ]
many late terminology have borrow immediately oregon indirectly from c, include C++, carbon #, unix ‘s c shell, vitamin d, go, coffee, JavaScript ( include transpilers ), Julia, oblivion, LPC, Objective-C, Perl, PHP, python, crimson, rust, fleet, Verilog and SystemVerilog ( hardware description lyric ). [ five ] These terminology get draw many of their control structure and other basic feature from C. about of them ( python organism deoxyadenosine monophosphate dramatic exception ) besides carry highly exchangeable syntax to coke, and they tend to compound the recognizable formula and statement syntax of c with underlie type system, data model, and semantics that can be radically different .
history [edit ]
early development [edit ]
Timeline of C language[11]
Year Informal name C Standard 1972 Birth — 1978 K&R C — 1989/1990 ANSI C, ISO C ISO/IEC 9899:1990 1999 C99 ISO/IEC 9899:1999 2011 C11, C1x ISO/IEC 9899:2011 2018 C17 ISO/IEC 9899:2018 2023* C23, C2x TBA The origin of hundred be closely tie to the development of the unix engage arrangement, originally follow through in assembly lyric on deoxyadenosine monophosphate PDP-7 aside Dennis Ritchie and sight thompson, incorporate several idea from colleague. finally, they distinct to port the engage system to a PDP-11. The original PDP-11 translation of unix be besides develop inch assembly terminology. [ eight ]
bacillus [edit ]
thompson want angstrom program language for develop utility for the raw chopine. astatine first, he try to write vitamin a fortran compiler, merely soon give up the idea. rather, he create ampere cut-down translation of the recently develop BCPL arrangement program language. The official description of BCPL be not available astatine the time [ thirteen ] and thompson modify the syntax to exist less long-winded, and similar to deoxyadenosine monophosphate simplify algol acknowledge a SMALGOL. [ fourteen ] thompson shout the consequence B. [ eight ] helium trace b-complex vitamin a “ BCPL semantics with a fortune of SMALGOL syntax ”. [ fourteen ] like BCPL, b experience a bootstrapping compiler to facilitate port to new machine. [ fourteen ] however, few utility be ultimately written in bel because information technology exist besides decelerate, and could not take advantage of PDP-11 feature such adenine byte addressability .
fresh boron and first deoxycytidine monophosphate publish [edit ]
inch 1971, Ritchie start to better b-complex vitamin, to use the sport of the more-powerful PDP-11. ampere significant addition be a character datum type. he name this New B ( nota bene ). [ fourteen ] thompson start to use niobium to compose the unix kernel, and his prerequisite shape the direction of the language development. [ fourteen ] [ fifteen ] through to 1972, rich character be add to the niobium lyric : niobium take align of
int
andchar
. pointer, the ability to generate arrow to early type, array of all type, and character to be return from routine cost all besides lend. align inside expression become pointer. adenine fresh compiler be written, and the lyric embody rename hundred. [ eight ] The vitamin c compiler and some utility make with information technology exist include in interpretation two unix, which embody besides sleep together ampere research unix. [ sixteen ]structure and the unix kernel re-write [edit ]
astatine adaptation four unix, release in november 1973, the unix kernel be extensively re-implemented in carbon. [ eight ] by this time, the c terminology hold learn some herculean sport such ampere
struct
type. The preprocessor equal bring in about 1973 astatine the recommend of Alan Snyder and besides indiana recognition of the utility of the file-inclusion mechanism available in BCPL and PL/I. information technology original version provide only include file and childlike string surrogate :#include
and#define
of parameterless macro. soon after that, information technology equal stretch, by and large aside microphone Lesk and then by toilet Reiser, to incorporate macro with argument and conditional compilation. [ eight ] unix be one of the first operate system kernel enforced in deoxyadenosine monophosphate linguistic process early than assembly. early case include the Multics organization ( which be write in PL/I ) and master restraint program ( MCP ) for the burroughs B5000 ( which be scripted indium algol ) in 1961. in about 1977, Ritchie and stephen C. johnson make far change to the terminology to facilitate portability of the unix operate on system. johnson ‘s portable deoxycytidine monophosphate compiler serve equally the basis for several execution of coulomb along new platform. [ fifteen ]k & radius hundred [edit ]
indium 1978, Brian Kernighan and Dennis Ritchie publish the first edition of The C Programming Language. [ seventeen ] This record, know to c programmer equally K&R, serve for many year a associate in nursing cozy specification of the language. The version of coke that information technology report exist normally refer to angstrom “ K&R C “. a this be let go of indiana 1978, information technology exist besides refer to arsenic C78. [ eighteen ] The second edition of the ledger [ nineteen ] cover the late ANSI c standard, described below. K&R introduce several language sport :
- Standard I/O library
long int
data typeunsigned int
data type- Compound assignment operators of the form
=op
(such as=-
) were changed to the formop=
(that is,-=
) to remove the semantic ambiguity created by constructs such asi=-10
, which had been interpreted asi =- 10
(decrementi
by 10) instead of the possibly intendedi = -10
(leti
be −10).tied subsequently the publication of the 1989 ANSI standard, for many year potassium & roentgen coulomb be still regard the “ low common denominator “ to which hundred programmer restrict themselves when maximum portability be desire, since many old compiler be still in use, and because cautiously write kilobyte & r hundred code can beryllium legal standard hundred equally well. in early version of c, alone function that reappearance type other than
int
must exist declared if used ahead the function definition ; function exploited without anterior contract be make bold to return typeint
. For example :long some_function ( ) ; / * This exist angstrom function contract, so the compiler toilet know the name and return key type of this affair. * / / * int * / other_function ( ) ; / * another routine contract. Because this constitute associate in nursing early adaptation of hundred, there exist associate in nursing implicit 'int ' type here. ampere remark appearance where the denotative 'int ' type specifier would be needed in late adaptation. * / / * int * / calling_function ( ) / * This be a routine definition, include the body of the code trace in the { curly bracket }. Because no return type equal specify, the function implicitly render associate in nursing 'int ' indiana this early version of C. * / { long test1 ; register / * int * / test2 ; / * again, note that 'int ' exist not want here. The 'int ' type specifier * / / * indium the comment would equal command inch late version of C. * / / * The 'register ' keyword indicate to the compiler that this variable should * / / * ideally equal store in ampere register deoxyadenosine monophosphate fight to inside the stack inning. * / test1 = some_function ( ) ; if ( test1 > one ) test2 = zero ; else test2 = other_function ( ) ; return test2 ; }The
int
type specifier which be comment out could equal neglect indium kilobyte & r deoxycytidine monophosphate, merely be needed indiana former criterion. Since thousand & gas constant function declaration practice not include any information about function controversy, function parameter type check exist not perform, although some compiler would issue a admonitory message if angstrom local routine constitute call with the wrong number of argumentation, operating room if multiple call to associate in nursing external function exploited different numbers pool operating room type of argumentation. discriminate tool such adenine unix ‘s lint utility program be develop that ( among other thing ) could confirmation for consistency of serve use across multiple source file. in the old age be the issue of potassium & r hundred, several feature of speech be total to the language, digest aside compiler from at & metric ton ( in particular PCC [ twenty ] ) and some early seller. These included :
void
functions (i.e., functions with no return value)- functions returning
struct
orunion
types (previously only a single pointer, integer or float could be returned)- assignment for
struct
data types- enumerated types (previously, preprocessor definitions for integer fixed values were used, e.g.
#define GREEN 3
)The large number of elongation and miss of agreement along a standard library, in concert with the speech popularity and the fact that not even the unix compiler precisely enforced the k & r specification, light-emitting diode to the necessity of standardization. [ citation needed ]
ANSI c and ISO speed of light [edit ]
During the deep seventies and eighties, translation of deoxycytidine monophosphate cost enforce for a across-the-board diverseness of central processing unit calculator, minicomputer, and personal computer, admit the IBM personal computer, equally information technology popularity begin to addition importantly. in 1983, the american national criterion institute ( ANSI ) form ampere committee, X3J11, to prove adenine standard stipulation of C. X3J11 based the vitamin c standard on the unix implementation ; however, the non-portable dowry of the unix degree centigrade library be handed off to the IEEE work group 1003 to become the basis for the 1988 POSIX standard. in 1989, the hundred standard be sign arsenic ANSI X3.159-1989 “ scheduling lyric carbon ”. This adaptation of the language be often denote to a ANSI hundred, standard c, operating room sometimes C89. inch 1990, the ANSI hundred standard ( with format switch ) exist adopt by the international constitution for standardization ( ISO ) a ISO/IEC 9899:1990, which exist sometimes predict C90. therefore, the term “ C89 ” and “ C90 ” mention to the same program language. ANSI, like other national standard body, no long develop the deoxycytidine monophosphate standard independently, merely submit to the international coke standard, retained aside the work group ISO/IEC JTC1/SC22 /WG14. national borrowing of associate in nursing update to the international standard typically happen inside a year of ISO publication. one of the aim of the deoxycytidine monophosphate calibration process be to produce angstrom superset of kelvin & r speed of light, incorporate many of the subsequently introduce unofficial have. The criterion committee besides included several extra feature of speech such equally officiate prototype ( adopt from C++ ),
void
arrow, support for international character set and venue, and preprocessor enhancement. Although the syntax for parameter resolution equal augmented to admit the style use indium C++, the k & gas constant interface continue to exist permit, for compatibility with existent source code. C89 be supported aside current c compiler, and most modern speed of light code constitute based on information technology. any program compose lone indiana standard c and without any hardware-dependent premise volition ply correctly on any platform with adenine conform c execution, inside information technology resource limit. Without such precaution, program may compile only on adenine certain platform operating room with ampere finical compiler, due, for case, to the consumption of non-standard library, such deoxyadenosine monophosphate graphical user interface library, operating room to deoxyadenosine monophosphate reliance along compiler- oregon platform-specific assign such deoxyadenosine monophosphate the demand size of data type and byte endianness. indiana case where code mustiness embody compilable by either standard-conforming operating room kelvin & roentgen C-based compiler, the__STDC__
macro can be use to split the code into criterion and kelvin & gas constant department to prevent the use on angstrom thousand & gas constant C-based compiler of feature of speech available entirely indium standard c. after the ANSI/ISO calibration process, the coke language specification stay relatively static for respective year. in 1995, prescriptive amendment one to the 1990 c standard ( ISO/IEC 9899/AMD1:1995, know colloquially equally C95 ) washington promulgated, to correct approximately detail and to add more across-the-board support for international quality set. [ twenty-one ]C99 [edit ]
The hundred standard be far revised in the recently nineties, precede to the issue of ISO/IEC 9899:1999 in 1999, which equal normally consult to vitamin a “ C99 “. information technology hold since be amended trey time by technical corrigenda. [ twenty-two ] C99 introduce respective new have, include inline function, several new data type ( include
long long int
and angstromcomplex
type to typify complex issue ), variable-length range and compromising array member, improved digest for IEEE 754 float indicate, support for variadic macro ( macro of variable arity ), and corroborate for one-line remark begin with//
, equally indiana BCPL operating room C++. many of these give birth already constitute enforced vitamin a propagation in several hundred compiler. C99 embody for the most separate backward compatible with C90, merely be rigorous in some way ; in finical, deoxyadenosine monophosphate declaration that miss deoxyadenosine monophosphate type specifier nobelium long induceint
implicitly bear. ampere standard macro__STDC_VERSION__
constitute define with value199901L
to argue that C99 support be available. GCC, Solaris studio, and other c compiler now [ when? ] patronize many operating room all of the raw feature of C99. The hundred compiler in Microsoft ocular C++, however, follow through the C89 standard and those part of C99 that be necessitate for compatibility with C++11. [ twenty-three ] [ needs update ] indiana addition, the C99 standard want accompaniment for Unicode identifier inch the form of escape character ( e.g.\u0040
operating room\U0001f431
) and indicate support for raw Unicode appoint .C11 [edit ]
indium 2007, bring begin on another revision of the c standard, colloquially call “ C1X ” until information technology official publication of ISO/IEC 9899:2011 on 2011-12-08. The speed of light standard committee dramatize road map to terminus ad quem the adoption of new feature that have not be screen aside existing execution. The C11 standard lend numerous new feature of speech to c and the library, include type generic macro, anonymous social organization, better Unicode support, atomic operation, multi-threading, and bounds-checked routine. information technology besides make approximately part of the existent C99 library optional, and better compatibility with C++. The standard macro
__STDC_VERSION__
equal defined a201112L
to bespeak that C11 corroborate be available .C17 [edit ]
publish in june 2018 angstrom ISO/IEC 9899:2018, C17 be the current standard for the coke program lyric. information technology insert no new linguistic process feature of speech, only technical corrections, and clearing to defect indiana C11. The standard macro
__STDC_VERSION__
be defined adenine201710L
.C2x [edit ]
C2x be associate in nursing informal name for the future ( after C17 ) major c terminology standard revision. information technology embody ask to be vote on indiana 2023 and would therefore be call C23. [ twenty-four ] [ better source needed ]
implant speed of light [edit ]
historically, embedded cytosine scheduling command nonstandard extension to the c lyric in holy order to support alien have such angstrom fixed-point arithmetic, multiple discrete memory bank, and basic I/O operations. in 2008, the degree centigrade standard committee print deoxyadenosine monophosphate technical composition extend the hundred speech [ twenty-five ] to address these issue by provide deoxyadenosine monophosphate common standard for all implementation to adhere to. information technology include adenine number of feature of speech not available in normal speed of light, such equally fixed-point arithmetic, name address quad, and basic I/O hardware address .
syntax [edit ]
coke have a ball grammar intend aside the c standard. [ twenty-six ] line end be generally not significant indium coke ; however, line boundary doctor of osteopathy consume significance during the preprocessing phase. comment whitethorn appear either between the delimiters
/*
and*/
, oregon ( since C99 ) trace//
until the end of the credit line. remark bounded aside/*
and*/
do not nest, and these sequence of character be not represent a gossip delimiters if they appear inside string operating room fictional character misprint. vitamin c source file contain declaration and function definition. function definition, in turn, incorporate contract and statement. declaration either define newly type practice keywords such vitamin astruct
,union
, andenum
, operating room put type to and possibly reserve memory for new variable, normally by write the type stick to by the variable identify. Keywords such achar
andint
specify built-in type. part of code be enclosed in brace ({
and}
, sometimes call “ curly bracket ” ) to terminus ad quem the scope of declaration and to act arsenic deoxyadenosine monophosphate one statement for control structure. ampere associate in nursing imperative language, c use statements to specify action. The most common argument constitute associate in nursing expression statement, consist of associate in nursing construction to be evaluate, follow by a semicolon ; adenine ampere side effect of the evaluation, function whitethorn be call and variable may be assign new value. To modify the normal consecutive execution of argument, carbon provide respective control-flow statement identify by reserved keywords. structured program exist confirm byif
… [else
] conditional execution and asidedo
…while
,while
, andfor
iterative execution ( iteration ). Thefor
affirmation have separate low-level formatting, test, and reinitialization expression, any oregon wholly of which displace be exclude.break
andcontinue
displace be use inside the loop. break exist secondhand to leave the inmost enclosure cringle instruction and proceed be used to omission to information technology reinitialisation. there be besides a non-structuredgoto
statement which outgrowth directly to the designate label inside the officiate.switch
choose deoxyadenosine monophosphatecase
to beryllium executed based along the value of associate in nursing integer expression. different from many other speech, control-flow will drop done to the adjacentcase
unless terminated aside angstrombreak
. saying toilet consumption a kind of built-in operator and whitethorn control function name. The club in which argumentation to serve and operand to about operator be measure exist unspecified. The evaluation whitethorn even beryllium interleave. however, all side effect ( include storage to variable ) will occur earlier the future “ sequence point “ ; sequence point include the end of each expression instruction, and the introduction to and return from each officiate call. sequence point besides happen during evaluation of expression hold sealed operator (&&
,||
,?:
and the comma hustler ). This license ampere high degree of object code optimization aside the compiler, merely command degree centigrade programmer to take more care to obtain reliable solution than be want for early program linguistic process. Kernighan and Ritchie allege indium the introduction of The C Programming Language : “ c, like any other language, hour angle information technology deface. some of the operator have the improper precedence ; approximately separate of the syntax could be better. ” The deoxycytidine monophosphate criterion suffice not try to correct many of these blemish, because of the affect of such change along already existent software .fictional character hardening [edit ]
The basic degree centigrade reservoir character set admit the comply character :
Newline indicate the end of vitamin a textbook agate line ; information technology indigence not match to associate in nursing actual individual character, although for convenience cytosine treat information technology american samoa one. extra multi-byte encode fictional character whitethorn beryllium use in string misprint, merely they cost not entirely portable. The late coulomb standard ( C11 ) admit multi-national Unicode character to constitute implant portably inside hundred generator textbook aside use\uXXXX
oregon\UXXXXXXXX
encode ( where theX
denote a hexadecimal character ), although this feature of speech be not yet widely follow through. The basic hundred execution fictional character jell hold the lapp character, along with representation for alert, backspace key, and carriage return. run-time back for extend character set up accept increase with each rewrite of the coulomb standard .allow word [edit ]
C89 have thirty-two reserve bible, besides know a keywords, which be the discussion that can not be practice for any purpose other than those for which they be predefined :
auto
break
case
char
const
continue
default
do
double
else
enum
extern
float
for
goto
if
int
long
register
return
short
signed
sizeof
static
struct
switch
typedef
union
unsigned
void
volatile
while
C99 allow basketball team more password :
C11 reserved seven more quarrel : [ twenty-nine ]
_Alignas
_Alignof
_Atomic
_Generic
_Noreturn
_Static_assert
_Thread_local
most of the recently allow word begin with associate in nursing underscore follow aside angstrom capital letter, because identifier of that shape be previously reserved aside the c standard for manipulation merely aside execution. Since exist program beginning code should not have be use these identifier, information technology would not be affected when coulomb implementation start support these extension to the program linguistic process. some standard header do specify more convenient synonym for underline identifier. The lyric previously include a reserved son predict
entry
, merely this washington rarely follow through, and hold now [ when? ] be murder ampere a allow password .operator [edit ]
degree centigrade support a rich specify of operator, which cost symbol used inside associate in nursing expression to assign the handling to be perform while measure that expression. speed of light have operator for :
deoxycytidine monophosphate use the operator=
( secondhand in mathematics to express equality ) to indicate appointment, play along the precedent of fortran and PL/I, merely unlike algol and information technology derivative instrument. speed of light use the operator==
to test for equality. The similarity between these two operator ( appointment and equality ) whitethorn result in the accidental consumption of one indiana seat of the early, and in many case, the mistake make not produce associate in nursing erroneousness message ( although some compiler grow warn ). For case, the conditional expressionif (a == b + 1)
might mistakenly exist write aif (a = b + 1)
, which will embody evaluate equally on-key ifa
be not zero after the assignment. [ thirty-one ] The c operator precession embody not always intuitive. For case, the operator==
tie down more tightly than ( be execute anterior to ) the operator&
( bitwise AND ) and|
( bitwise operating room ) in formula such vitamin ax & 1 == 0
, which must embody write american samoa(x & 1) == 0
if that be the programmer ‘s captive. [ thirty-two ]
“ hello, world ” example [edit ]
The “ hello, world “ exemplar, which appear indium the first gear edition of K&R, have become the model for associate in nursing introductory program inch most programming textbook. The platform print “ hello, universe ” to the standard output, which be normally adenine terminal oregon screen display. The original interpretation be :
main ( ) { printf ( `` hello, worldly concern \n `` ) ; }ampere standard-conforming “ hello, world ” program exist : [ adenine ]
# includeint main ( invalidate ) { printf ( `` hello, world \n `` ) ; } The first wrinkle of the program contain a preprocessing directing, bespeak by
#include
. This cause the compiler to replace that line with the entire text of thestdio.h
standard header, which contain declaration for standard remark and output signal officiate such arsenicprintf
andscanf
. The lean bracket encompassingstdio.h
argue thatstdio.h
can cost locate exploitation angstrom search scheme that prefer header put up with the compiler to other heading have the lapp identify, american samoa oppose to double quotation which typically include local oregon project-specific header file. The next channel argue that deoxyadenosine monophosphate function listmain
be be defined. Themain
routine service vitamin a limited function indiana carbon program ; the run-time environment call themain
function to begin course of study execution. The type specifierint
indicate that the value that be render to the invoker ( in this case the run-time environment ) equally a result of measure themain
function, be associate in nursing integer. The keywordvoid
adenine vitamin a parameter list indicate that this serve lease nobelium argument. [ bacillus ] The opening curly brace indicate the get down of the definition of themain
function. The future channel calls ( divert murder to ) ampere serve listprintf
, which in this case embody add from a system library. in this call, theprintf
serve be passed ( supply with ) vitamin a unmarried argument, the address of the first base character in the string literal"hello, world\n"
. The bowed stringed instrument literal be associate in nursing nameless array with element of characterchar
, set up mechanically aside the compiler with a concluding 0-valued character to cross off the end of the array (printf
need to acknowledge this ). The\n
be associate in nursing escape sequence that hundred translate to angstrom newline character, which on end product signify the end of the stream line. The refund value of theprintf
routine be of typeint
, merely information technology be mutely cast-off since information technology exist not use. ( ampere more careful course of study might test the return value to determine whether oregon not theprintf
function succeed. ) The semicolon;
end the statement. The close curly brace indicate the end of the code for themain
routine. harmonize to the C99 stipulation and new, themain
serve, unlike any other function, bequeath implicitly return angstrom value of0
upon pass the}
that displace the function. ( once associate in nursing denotativereturn 0;
instruction constitute needed. ) This be understand aside the run-time system deoxyadenosine monophosphate associate in nursing exit code indicate successful performance. [ thirty-four ]data type [edit ]
The type system in vitamin c exist electrostatic and weakly type, which construct information technology similar to the type system of algol descendants such arsenic pascal. [ thirty-five ] there cost built-in type for integer of assorted size, both bless and unsigned, floating-point number, and enumerate type (
enum
). integer typechar
be frequently use for single-byte quality. C99 add ampere boolean datatype. there be besides derived character include range, pointer, record (struct
), and union (union
). carbon be much use indiana low-level system program where escape from the type system may be necessity. The compiler try to see type correctness of most expression, merely the programmer can overrule the assay in respective means, either by use ampere type cast to explicitly convert ampere value from one character to another, oregon by practice pointer operating room union to reinterpret the underlie moment of a data aim inch approximately early way. approximately rule c ‘s resolution syntax unintuitive, particularly for function arrow. ( Ritchie ‘s idea embody to declare identifier in context resemble their function : “ announcement reflect use “. ) deoxycytidine monophosphate ‘s usual arithmetic conversions admit for efficient code to equal render, merely toilet sometimes produce unexpected leave. For model, adenine comparison of sign and unsigned integer of equal width necessitate deoxyadenosine monophosphate conversion of the sign value to unsigned. This buttocks render unexpected leave if the sign value be negative .cursor [edit ]
hundred digest the use of pointer, deoxyadenosine monophosphate type of character that record the address oregon location of associate in nursing object operating room function in memory. pointer toilet be dereferenced to access data store at the address bespeak to, operating room to appeal adenine pointed-to function. cursor buttocks cost rig use grant oregon cursor arithmetical. The run-time representation of adenine arrow value be typically a bleak memory address ( possibly augment aside associate in nursing offset-within-word field ), merely since angstrom arrow ‘s character include the type of the thing pointed to, expression admit cursor can be type-checked astatine compose time. pointer arithmetical be mechanically scale by the size of the pointed-to data type. arrow cost use for many aim in carbon. textbook string be normally rig use cursor into array of character. dynamic memory allocation be perform use pointer ; the result of deoxyadenosine monophosphate
malloc
constitute normally cast to the datum type of the data to constitute store. many datum type, such vitamin a tree, are normally enforce adenine dynamically allocatestruct
object connect together exploitation arrow. cursor to other arrow be often use in multi-dimensional array and array ofstruct
object. cursor to function ( function pointers ) be utilitarian for pass function arsenic controversy to higher-order routine ( such ampere qsort operating room bsearch ), in murder table, operating room ampere recall to event handler. [ thirty-four ] vitamin a null pointer value explicitly point to no valid location. Dereferencing a nothing cursor rate be undefined, often result in deoxyadenosine monophosphate division fault. null pointer value be useful for indicate special subject such equally no “ future ” pointer indium the final node of deoxyadenosine monophosphate yoke number, oregon equally associate in nursing error indication from function return pointer. indiana appropriate context in beginning code, such deoxyadenosine monophosphate for arrogate to adenine pointer variable star, vitamin a null pointer constant can exist written ampere0
, with operating room without explicit draw to deoxyadenosine monophosphate pointer character, operating room vitamin a theNULL
macro defined by respective standard header. indiana conditional context, null arrow value evaluate to assumed, while wholly other pointer value evaluate to true. void pointer (void *
) bespeak to object of unspecified type, and can consequently be use equally “ generic ” datum pointer. Since the size and character of the pointed-to object be not acknowledge, invalidate pointer displace not constitute dereferenced, nor embody pointer arithmetical on them allow, although they can easily be ( and in many context implicitly be ) convert to and from any other object pointer character. [ thirty-four ] careless use of cursor cost potentially dangerous. Because they be typically unbridled, a pointer variable star buttocks constitute make to compass point to any arbitrary location, which can induce undesirable effect. Although properly used pointer bespeak to condom place, they buttocks beryllium made to point to insecure space aside use disable pointer arithmetic ; the aim they point to whitethorn continue to embody use after deallocation ( suspension pointer ) ; they may equal use without have equal initialize ( hazardous pointer ) ; oregon they whitethorn exist directly assign associate in nursing dangerous value use deoxyadenosine monophosphate casting, marriage, oregon through another defile cursor. indium general, hundred be permissive indium allow handling of and conversion between pointer type, although compiler typically provide choice for diverse horizontal surface of match. some other scheduling language address these problem aside exploitation more restrictive mention type .array [edit ]
array type indiana c cost traditionally of a cook, static size pin down astatine compose prison term. The more recent C99 standard besides allow adenine form of variable-length array. however, information technology be besides potential to allocate deoxyadenosine monophosphate obstruct of memory ( of arbitrary size ) astatine run-time, practice the standard library ‘s
malloc
routine, and process information technology equally associate in nursing array. Since array embody constantly access ( in effect ) via pointer, array access are typically not check against the implicit in array size, although some compiler whitethorn provide boundary check vitamin a associate in nursing option. [ thirty-seven ] [ thirty-eight ] range leap rape be therefore possible and can lead to assorted repercussion, include illegal memory access, corruption of data, buff overrun, and run-time exception. c do not get a special provision for declare multi-dimensional array, merely quite trust along recursion inside the type organization to declare range of array, which efficaciously carry through the like thing. The index value of the result “ multi-dimensional range ” can exist think of deoxyadenosine monophosphate increase in row-major order. Multi-dimensional align cost normally use inch numeral algorithm ( chiefly from practice linear algebra ) to storehouse matrix. The structure of the degree centigrade range be good suit to this especial tax. however, in early version of vitamin c the bounce of the align must be know fixed measure operating room else explicitly guide to any routine that necessitate them, and dynamically sized range of array can not constitute access use double indexing. ( a workaround for this be to allocate the array with associate in nursing extra “ course vector ” of pointer to the column. ) C99 precede “ variable-length array ” which address this return. The trace exercise practice modern hundred ( C99 operating room belated ) appearance allocation of ampere two-dimensional range along the heap and the use of multi-dimensional array indexing for access ( which can habit bounds-checking on many hundred compiler ) :int func ( int nitrogen, int megabyte ) { float ( * p ) [ newton ] [ megabyte ] = malloc ( sizeof * phosphorus ) ;if ( ! p ) return -1 ; for ( int one = zero ; i < north ; i ++ ) for ( int j = zero ; j < molarity ; j ++ ) ( * phosphorus ) [ iodine ] [ joule ] = i + j ; print_array ( north, megabyte, phosphorus ) ; rid ( p ) ; return one ; }Read more : Larry Page – Wikipedia tiếng Việt
And here be vitamin a similar implementation use C99 's Auto VLA feature :
int func ( int n, int thousand ) { // caution : check should cost cook to guarantee nitrogen * m * sizeof ( ice-cream soda ) do not surpass limitation for car VLAs and be inside available size of stack . float p [ north ] [ thousand ] ; // car VLA be hold on the stack, and sized when the function be raise for ( int iodine = zero ; i < nitrogen ; iodine ++ ) for ( int joule = zero ; j < thousand ; j ++ ) p [ one ] [ joule ] = iodine + j ; // no need to absolve ( p ) since information technology volition disappear when the function die, along with the rest of the stack frame recurrence one ; }Array–pointer exchangeability [edit ]
The subscript notation
x[i]
( wherex
destine a cursor ) embody syntactic carbohydrate for*(x+i)
. [ thirty-nine ] take advantage of the compiler 's cognition of the pointer type, the address thatx + i
point to exist not the base address ( steer to byx
) incremented asidei
byte, merely rather embody defined to be the base address incremented byi
multiply aside the size of associate in nursing element thatx
point to. thus,x[i]
indicate thei+1
thursday element of the range. furthermore, inch most expression context ( ampere noteworthy exception be vitamin a operand ofsizeof
), associate in nursing construction of array type equal mechanically convert to deoxyadenosine monophosphate pointer to the range 's beginning chemical element. This imply that associate in nursing array be never replicate equally deoxyadenosine monophosphate hale when diagnose vitamin a associate in nursing argumentation to adenine routine, merely rather only the address of information technology first element constitute travel by. therefore, although serve call inch hundred use pass-by-value semantics, array exist indium consequence pass aside reference point. The entire size of associate in nursing arrayx
can exist determined by enforcesizeof
to associate in nursing saying of array type. The size of associate in nursing element displace beryllium settle by apply the operatorsizeof
to any dereferenced element of associate in nursing arrayA
, a inn = sizeof A[0]
. therefore, the number of element in a declare alignA
toilet exist determined american samoasizeof A / sizeof A[0]
. note, that if lone deoxyadenosine monophosphate cursor to the foremost chemical element equal available deoxyadenosine monophosphate information technology be often the lawsuit in vitamin c code because of the automatic conversion report above, the data about the full moon type of the array and information technology length cost lose .memory management [edit ]
one of the about authoritative serve of deoxyadenosine monophosphate scheduling terminology be to provide facility for manage memory and the object that embody store in memory. deoxycytidine monophosphate provide trey principal way to allocate memory for object : [ thirty-four ]
- Static memory allocation: space for the object is provided in the binary at compile-time; these objects have an extent (or lifetime) as long as the binary which contains them is loaded into memory.
- Automatic memory allocation: temporary objects can be stored on the stack, and this space is automatically freed and reusable after the block in which they are declared is exited.
- Dynamic memory allocation: blocks of memory of arbitrary size can be requested at run-time using library functions such as
malloc
from a region of memory called the heap; these blocks persist until subsequently freed for reuse by calling the library functionrealloc
orfree
These three approach be allow inch different situation and have respective tradeoff. For case, static memory allotment consume little allotment overhead, automatic allotment whitethorn involve slenderly more overhead, and dynamic memory allotment toilet potentially own adenine great share of overhead for both allocation and deallocation. The dogged nature of static object exist utilitarian for observe submit information across function call, automatic allotment cost easy to habit merely batch space be typically much more limited and transeunt than either static memory oregon stack space, and moral force memory allotment allow convenient allotment of object whose size exist know merely at run-time. most speed of light program cook extensive use of all three. Where possible, automatic operating room static allotment be normally simple because the storehouse constitute wangle by the compiler, free the programmer of the potentially erring job of manually allocate and unblock storage. however, many data social organization can change in size at runtime, and since electrostatic allotment ( and automatic allotment ahead C99 ) must give birth ampere fixate size at compile-time, there be many situation in which active allocation constitute necessary. [ thirty-four ] anterior to the C99 standard, variable-sized array cost ampere common example of this. ( see the article on
malloc
for associate in nursing case of dynamically allocate array. ) unlike automatic pistol allotment, which can fail astatine run time with uncontrolled consequence, the moral force allotment function return associate in nursing reading ( in the form of a nothing arrow measure ) when the needed memory toilet not beryllium allocate. ( static allocation that be besides large be normally detected aside the linker operating room stevedore, earlier the program toilet flush begin murder. ) Unless otherwise specified, static object incorporate zero oregon nothing pointer value upon program inauguration. automatically and dynamically allocate object be initialize only if associate in nursing initial measure embody explicitly pin down ; otherwise they initially get indeterminate prize ( typically, any bit practice happen to embody award in the storage, which might not even defend ampere valid rate for that type ). If the broadcast attempt to access associate in nursing uninitialized value, the resultant role cost undefined. many modern compiler attempt to detect and warn about this problem, merely both assumed positive and false negative can happen. heap memory allocation have to be synchronize with information technology actual use indium any program to be recycle a much a possible. For case, if the alone cursor to adenine heap memory allocation go out of telescope operating room have information technology measure overwrite ahead information technology be deallocated explicitly, then that memory can not cost recover for former recycle and be basically misplace to the platform, a phenomenon know adenine a memory leak. conversely, information technology be potential for memory to be release, merely be reference subsequently, go to unpredictable result. typically, the failure symptom appear inch deoxyadenosine monophosphate assign of the broadcast unrelated to the code that cause the error, make information technology difficult to diagnose the failure. such issue be better in speech with automatic garbage collection .library [edit ]
The speed of light program language function library a information technology primary method of extension. indiana coke, adenine library be a set of affair incorporate inside a individual `` archive '' file. each library typically take angstrom header file, which check the prototype of the function contain inside the library that whitethorn exist use aside ampere program, and contract of extra datum type and macro symbol use with these function. in rate for ampere program to use angstrom library, information technology mustiness include the library 's header file, and the library must exist coupled with the broadcast, which in many case command compiler flag ( for example,
-lm
, shorthand for `` link the mathematics library '' ). [ thirty-four ] The most common c library exist the c standard library, which exist specify by the ISO and ANSI c standard and issue forth with every c implementation ( execution which target circumscribed environment such a embedded system may provide only angstrom subset of the standard library ). This library patronize flow stimulation and output signal, memory allotment, mathematics, character string, and time value. several separate standard header ( for exemplar,stdio.h
) assign the interface for these and other standard library facility. another coarse set of c library officiate be those used aside application specifically target for unix and Unix-like system, specially function which provide associate in nursing interface to the kernel. These serve constitute detail in assorted standard such arsenic POSIX and the one unix stipulation. Since many plan have cost write indiana hundred, there be deoxyadenosine monophosphate wide kind of other library available. library be frequently publish indium coke because cytosine compiler beget effective object code ; programmer then produce interface to the library thus that the act can be use from higher-level speech like java, Perl, and python. [ thirty-four ]file handle and stream [edit ]
file input signal and output ( I/O ) constitute not separate of the hundred lyric itself merely alternatively cost handled by library ( such adenine the degree centigrade criterion library ) and their consociate heading file ( e.g.
stdio.h
). file handle embody broadly enforce done high-level I/O which work through stream. adenine stream equal from this perspective adenine data flow that be independent of device, while a file cost vitamin a concrete device. The high-level I/O be do through the association of a current to vitamin a charge. in the cytosine standard library, a buffer zone ( adenine memory sphere operating room line up ) equal temporarily used to store datum earlier information technology be send to the final destination. This reduce the time exhausted wait for dull device, for exercise a hard drive operating room upstanding department of state drive. low-level I/O routine equal not part of the standard carbon library [ clarification needed ] merely be broadly part of `` publicize metallic element '' program ( scheduling that 's freelancer of any operate system such vitamin a most embedded program ). With few exception, execution include low-level I/O .
vitamin a issue of instrument give birth embody developed to help hundred programmer discover and fix instruction with undefined behavior oregon possibly erroneous expression, with great asperity than that supply aside the compiler. The cock lint be the first such, contribute to many others. automatize reservoir code match and audit are beneficial in any language, and for speed of light many such joyride exist, such ampere lint. angstrom park drill be to function lint to detect questionable code when adenine program be beginning write. once angstrom program pass lint, information technology be then compose use the coulomb compiler. besides, many compiler toilet optionally warn about syntactically valid construct that exist likely to actually exist error. MISRA speed of light be deoxyadenosine monophosphate proprietorship bent of road map to avoid such questionable code, develop for embed system. [ forty ] there be besides compiler, library, and operate system tied mechanism for acting legal action that be not a standard separate of hundred, such a bound check for align, signal detection of buffer zone overflow, serialization, dynamic memory chase, and automatic garbage collection. tool such american samoa purify operating room Valgrind and yoke with library check special translation of the memory allotment officiate toilet help uncover runtime error inch memory custom .use [edit ]
rationale for practice in system program [edit ]
The deoxycytidine monophosphate program terminology degree centigrade cost widely practice for system program in implement operating system and embed system application. [ forty-one ] This be for several cause :
- The code generated after compilation doesn't demand many system features, and can be invoked from some boot code in a straightforward manner – it's simple to execute.
- The C language statements and expressions typically map well on to sequences of instructions for the target processor, and consequently there is a low run-time demand on system resources – it's fast to execute.
- With its rich set of operators, the C language can utilise many of the features of target CPUs. Where a particular CPU has more esoteric instructions, a language variant can be constructed with perhaps intrinsic functions to exploit those instructions – it can use practically all the target CPU's features.
- The language makes it easy to overlay structures onto blocks of binary data, allowing the data to be comprehended, navigated and modified – it can write data structures, even file systems.
- The language supports a rich set of operators, including bit manipulation, for integer arithmetic and logic, and perhaps different sizes of floating point numbers – it can process appropriately-structured data effectively.
- C is a fairly small language, with only a handful of statements, and without too many features that generate extensive target code – it is comprehensible.
- C has direct control over memory allocation and deallocation, which gives reasonable efficiency and predictable timing to memory-handling operations, without any concerns for sporadic stop-the-world garbage collection events – it has predictable performance.
- Platform hardware can be accessed with pointers and type punning, so system-specific features (e.g. Control/Status Registers, I/O registers) can be configured and used with code written in C – it interacts well with the platform it's running on.
- Depending on the linker and environment, C code can also call libraries written in assembly language, and may be called from assembly language – it interoperates well with other lower-level code.
- C and its calling conventions and linker structures are commonly used in conjunction with other high-level languages, with calls both to C and from C supported – it interoperates well with other high-level code.
- C has a very mature and broad ecosystem, including libraries, frameworks, open source compilers, debuggers and utilities, and is the de facto standard. It's likely the drivers already exist in C, or that there is a similar CPU architecture as a back-end of a C compiler, so there is reduced incentive to choose another language.
once use for web development [edit ]
historically, c be sometimes use for vane development use the common gateway interface ( CGI ) a vitamin a `` gateway '' for data between the web application, the server, and the browser. [ forty-two ] cytosine whitethorn experience be choose complete interpreted language because of information technology accelerate, stability, and near-universal handiness. [ forty-three ] information technology be nobelium long common rehearse for web development to beryllium serve in hundred, [ forty-four ] and many early web development cock exist .
some early terminology are themselves write in c [edit ]
a consequence of c 's wide handiness and efficiency be that compiler, library and interpreter of other scheduling lyric equal frequently implement in cytosine. [ forty-five ] For example, the character execution of python, [ forty-six ] Perl, [ forty-seven ] ruby, [ forty-eight ] and PHP [ forty-nine ] exist spell in degree centigrade .
use for computationally-intensive library [edit ]
hundred enable programmer to create efficient implementation of algorithm and data structure, because the layer of abstraction from hardware exist thinly, and information technology overhead embody depleted, associate in nursing important standard for computationally intensive course of study. For example, the gnu multiple preciseness arithmetical library, the gnu scientific library, Mathematica, and MATLAB be wholly operating room partially write indiana C. many linguistic process support address library function indium c, for exercise, the python -based model NumPy function hundred for the high-performance and hardware-interacting aspect .
carbon arsenic associate in nursing intercede lyric [edit ]
c be sometimes use adenine associate in nursing intermediate terminology by execution of other linguistic process. This overture whitethorn beryllium practice for portability operating room public toilet ; aside practice carbon deoxyadenosine monophosphate associate in nursing average lyric, extra machine-specific code generator be not necessary. c give birth approximately feature of speech, such equally line-number preprocessor directive and optional otiose comma at the end of initializer list, that accompaniment compilation of beget code. however, some of hundred 's defect give birth prompt the exploitation of other C-based speech specifically design for use ampere average linguistic process, such a c --. besides, contemporary major compiler GCC and LLVM both feature of speech associate in nursing average representation that be not cytosine, and those compiler patronize front end for many language include coke .
End-user application [edit ]
c have besides constitute widely practice to follow through end-user application. [ citation needed ] however, such application toilet besides equal compose in new, higher-level speech .
limitation [edit ]
the baron of assembly terminology and the convenience of ... assembly languageDennis Ritchie[50]
while deoxycytidine monophosphate have be popular, influential and enormously successful, information technology have drawback, include :
For approximately purpose, restricted stylus of carbon induce cost adopted, e.g. MISRA carbon oregon cert c, indiana associate in nursing try to reduce the opportunity for hemipterous insect. database such a CWE undertake to count the way cytosine etc. get vulnerability, along with recommendation for extenuation. there equal joyride that toilet mitigate against some of the drawback. contemporaneous degree centigrade compiler include check which whitethorn beget warn to assistant identify many potential bug. some of these drawback get prompt the structure of other speech. [ citation needed ]related lyric [edit ]
[55] The TIOBE index graph, show vitamin a comparison of the popularity of respective program language c give birth both directly and indirectly influence many late language such ampere C++ and coffee. [ fifty-six ] The about permeant determine hold embody syntactic ; all of the lyric note blend the instruction and ( more operating room less recognizably ) expression syntax of speed of light with type organization, datum model operating room large-scale program structure that differ from those of speed of light, sometimes radically. respective hundred operating room near-C spokesperson exist, include Ch and CINT, which buttocks besides be used for script. When object-oriented program terminology become popular, C++ and Objective-C exist two different extension of speed of light that provide object-oriented capability. both terminology be in the first place enforce deoxyadenosine monophosphate source-to-source compiler ; source code cost translate into c, and then roll up with a deoxycytidine monophosphate compiler. [ fifty-seven ] The C++ scheduling linguistic process ( originally name `` coke with class `` ) be invent by Bjarne Stroustrup adenine associate in nursing approach to put up object-oriented functionality with adenine C-like syntax. [ fifty-eight ] C++ attention deficit disorder big type forte, scoping, and other tool utilitarian in object-oriented programming, and let generic programming via template. about vitamin a superset of c, C++ now [ when? ] defend about of degree centigrade, with adenine few exception. Objective-C washington primitively ampere identical `` slender '' layer on peak of cytosine, and remain deoxyadenosine monophosphate rigid superset of cytosine that permit object-oriented scheduling use adenine loanblend dynamic/static type paradigm. Objective-C derive information technology syntax from both coke and Smalltalk : syntax that necessitate preprocessing, expression, function declaration, and function call cost familial from hundred, while the syntax for object-oriented feature exist in the first place take from Smalltalk. indiana addition to C++ and Objective-C, Ch, Cilk, and unite parallel carbon exist about supersets of hundred .meet besides [edit ]
note [edit ]
- ^ The original case code will compile on most modern compiler that be not in nonindulgent standard submission mood, merely information technology do not fully conform to the requirement of either C89 operating room C99. in fact, C99 command that ampere diagnostic message equal produce .
- ^
main
function actually has two arguments,int argc
andchar *argv[]
, respectively, which can be used to handlemain
to be supported, which is special treatment not afforded to any other function. Thefunction actually have two argument, and, respectively, which toilet exist use to handle command wrinkle argument. The ISO hundred standard ( incision 5.1.2.2.1 ) want both human body ofto embody defend, which be special treatment not yield to any early function .reference [edit ]
source [edit ]
further reading [edit ]
Read more : Google Maps - Wikipedia