C (programming language): Difference between revisions

[pending revision][accepted revision]
Content deleted Content added
No edit summary
Tags: Reverted Mobile edit Mobile web edit
Undid revision 1307694532 by Elrondil (talk) - alloca is not in any standard and does not allow one to allocate blocks of memory of arbitrary size
 
(161 intermediate revisions by 64 users not shown)
Line 4:
{{pp-pc}}
{{Use mdy dates|date=October 2024}}
{{CS1 config |mode=cs1 }}
{{Infobk +0072827u2292020137jj
{{Infobox programming language
.
 
 
Jeye0cake box programming language
| name = C
| logo = The C Programming Language logo.svg
| logo alt = Text says "The C Programming Language"
| logo caption = Logotype used on the cover of the first edition of ''[[The C Programming Language]]''<ref name="C in a Nutshell">{{Cite book|url={{GBurl|id=4Mfe4sAMFUYC}}|title=C in a Nutshell|last1=Prinz|first1=Peter|last2=Crawford|first2=Tony|date=December 16, 2005|publisher=O'Reilly Media, Inc.|isbn=9780596550714|page=3|language=en}}</ref>
| paradigm = [[Multi-paradigm]]: [[Imperative programming|imperative]] ([[Procedural programming|procedural]]), [[structured programming|structured]]
Line 25 ⟶ 21:
| influenced = [[:Category:C programming language family|Numerous]]: [[AMPL]], [[AWK]], [[C shell|csh]], [[C++]], [[C--]], [[C Sharp (programming language)|C#]], [[Objective-C]], [[D (programming language)|D]], [[Go (programming language)|Go]], [[Java (programming language)|Java]], [[JavaScript]], [[JS++]], [[Julia (programming language)|Julia]], [[Limbo (programming language)|Limbo]], [[LPC (programming language)|LPC]], [[Perl]], [[PHP]], [[Pike (programming language)|Pike]], [[Processing (programming language)|Processing]], [[Python (programming language)|Python]], [[Rust (programming language)|Rust]], [[Seed7]], [[V (programming language)|V (Vlang)]], [[Vala (programming language)|Vala]], [[Verilog]] (HDL),<ref name="vinsp">{{cite web|title=Verilog HDL (and C)|url=http://cs.anu.edu.au/courses/ENGN3213/lectures/lecture6_VERILOG_2010.pdf|date=June 3, 2010|access-date=August 19, 2013|publisher=The Research School of Computer Science at the Australian National University|quote=1980s: Verilog first introduced; Verilog inspired by the C programming language|url-status=dead|archive-url=https://web.archive.org/web/20131106064022/http://cs.anu.edu.au/courses/ENGN3213/lectures/lecture6_VERILOG_2010.pdf|archive-date=November 6, 2013}}</ref> [[Nim (programming language)|Nim]], [[Zig (programming language)|Zig]]
| operating system = [[Cross-platform]]
| year = {{start date and age|1972}}<ref name="dottcl_2">{{harvtxt|Ritchieefn |1993}}: "Thompson had made a brief attempt to produce a system coded in an early version of C—before structures—in 1972, but gave up the effort."</ref>{{sfnp|Ritchie|1993a|p=9}}{{sfnp|Ritchie|1993b|p=9}}{{sfnp|Ritchie|2003}}}}
| influenced by = [[B (programming language)|B]] ([[BCPL]], [[CPL (programming language)|CPL]]), [[ALGOL 68]],<ref name="dottcl_1">{{harvtxt|Ritchie|1993}}:efn |"The scheme of type composition adopted by C owes considerable debt to Algol 68, although it did not, perhaps, emerge in a form that Algol's adherents would approve of."</ref>{{sfnp|Ritchie|1993a|p=8}}{{sfnp|Ritchie|1993b|p=8}}{{sfnp|Ritchie|2003}} }} [[PL/I]], [[FORTRANFortran]]
| file ext = .c, .h
| website = {{ubl|{{URL|https://www.c-language.org/|c-language.org}}|{{URL|https://www.iso.org/standard/82075.html|iso.org}}<br /> |{{URL|www.open-std.org/jtc1/sc22/wg14/|open-std.org}}}}
| wikibooks = C Programming
}}
 
'''C''' (''pronounced''{{efn|Pronounced {{IPAc-en|'|s|iː}}'' –, like the letter {{gloss |[[c]]'')}}.<ref>{{cite web |title=The name is based on, and pronounced like the letter C in the English alphabet |url=https://eng.ichacha.net/pronounce/the%20c%20programming%20language.html |url-status=live |archive-url=https://web.archive.org/web/20221117151137/https://eng.ichacha.net/pronounce/the%20c%20programming%20language.html |archive-date=November 17, 2022 |access-date=November 17, 2022 |website=the c programming language sound |publisher=English Chinese Dictionary |language=en-US}}</ref>}} is a [[general-purpose programming language]]. It was created in the 1970s by [[Dennis Ritchie]] and remains very widely used and influential. By design, C's featuresgives cleanlythe reflect[[programmer]] relatively direct access to the capabilitiesfeatures of the targetedtypical [[Central processing unit|CPUsCPU]] architecture, customized for the target [[Instruction set architecture|instruction set]]. It has foundbeen lastingand usecontinues into be used to implement [[operating system]]s code (especially in [[Kernel (operating system)|kernels]]<ref>{{Cite web |last=Munoz |first=Daniel |title=After All These Years, the World is Still Powered by C Programming {{!}} Toptal |url=https://www.toptal.com/c/after-all-these-years-the-world-is-still-powered-by-c-programming |access-date=June 15, 2024 |website=Toptal Engineering Blog}}</ref>), [[device driver]]s, and [[protocol stack]]s, but its use in [[application software]] has been decreasing.<ref>{{cite web |date=August 9, 2016 |title=C Language Drops to Lowest Popularity Rating |url=https://www.developer.com/news/c-language-drops-to-lowest-popularity-rating/ |url-status=dead |archive-url=https://web.archive.org/web/20220822225609/https://www.developer.com/news/c-language-drops-to-lowest-popularity-rating/ |archive-date=August 22, 2022 |access-date=August 1, 2022 |website=Developer.com |language=en-US}}</ref> C is commonly used on computer architecturescomputers that range from the largest [[supercomputer]]s to the smallest [[microcontroller]]s and [[embedded system]]s.
 
A successor to the programming language [[B (programming language)|B]], C was originally developed at [[Bell Labs]] by Ritchie between 1972 and 1973 to construct utilities running on [[Unix]]. It was applied to re-implementing the kernel of the Unix operating system.<ref name="sigplan" />{{sfnp|Ritchie|1993a}} During the 1980s, C gradually gained popularity. It has become one of the most widely used [[programming language]]s,<ref name="langpop">{{cite web |url=http://www.langpop.com/ |title=Programming Language Popularity |year=2009 |access-date=January 16, 2009 |url-status=dead |archive-url= https://web.archive.org/web/20090116080326/http://www.langpop.com/ |archive-date=January 16, 2009}}</ref><ref name="TIOBE-2009">{{cite web |url=http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html | title=TIOBE Programming Community Index |year=2009 |access-date=May 6, 2009 |url-status=dead |archive-url= https://web.archive.org/web/20090504181627/http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html |archive-date=May 4, 2009}}</ref> with C [[compiler]]s available for practically all modern [[computer architecture]]s and [[operating system]]s. The book ''[[The C Programming Language]]'', co-authored by the original language designer, served for many years as the ''de facto'' standard for the language.<ref name="ward198308">{{cite news |last=Ward |first=Terry A. |url=https://archive.org/stream/byte-magazine-1983-08/1983_08_BYTE_08-08_The_C_Language#page/n267/mode/2up |title=Annotated C / A Bibliography of the C Language |work=Byte |date=August 1983 |access-date=January 31, 2015 |pages=268}}</ref><ref name="C in a Nutshell"/> C has been standardized since 1989 by the [[American National Standards Institute]] (ANSI) and, subsequently, jointly by the [[International Organization for Standardization]] (ISO) and the [[International Electrotechnical Commission]] (IEC).
 
C is an [[Imperative programming|imperative]] [[Procedural programming|procedural]] language, supporting [[structured programming]], [[lexical variable scope]], and [[Recursion (computer science)|recursion]], with a [[static type system]]. It was designed to be [[compiled]] to provide [[Low-level programming language|low-level]] access to [[Computer memory|memory]] and language constructs that map efficiently to [[machine instructions]], all with minimal [[Runtime system|runtime support]]. Despite its low-level capabilities, the language was designed to encourage cross-platform programming. A [[Specification (technical standard)|standards]]-compliant C program written with [[Software portability|portability]] in mind can be compiled for a wide variety of computer platforms and operating systems with few changes to its source code.
 
Although neither C nor its standard library provide some popular features found in other languages, it is flexible enough to support them. For example, [[Object-oriented programming|object orientation]] and [[garbage collection (computer science)|garbage collection]] are provided by external libraries [[GLib Object System]] and [[Boehm garbage collector]], respectively.
 
Since 2000, C has consistently ranked among the top four languages in the [[TIOBE index]], a measure of the popularity of programming languages.<ref>{{cite web|title=TIOBE Index for September 2024|url=https://www.tiobe.com/tiobe-index/|access-date=September 20, 2024|archive-date=September 18, 2024|archive-url=https://web.archive.org/web/20240918165843/https://www.tiobe.com/tiobe-index/|url-status=live}}</ref>
 
== OverviewCharacteristics ==
[[File:Ken n dennis.jpg|thumb|[[Dennis Ritchie]] (right), the inventor of the C programming language, with [[Ken Thompson]]]]
 
The C language exhibits the following characteristics:
C is an [[Imperative programming|imperative]], procedural language in the [[ALGOL]] tradition. It has a static [[type system]]. In C, all [[executable code]] is contained within [[subroutine]]s (also called "functions", though not in the sense of [[functional programming]]). [[Function parameter]]s are passed by value, although [[Array (data type)|arrays]] are passed as [[Pointer (computer programming)|pointers]], i.e. the address of the first item in the array. ''Pass-by-reference'' is simulated in C by explicitly passing pointers to the thing being referenced.
{{Div col |colwidth=30em}}
* [[Free-form language|Free-form]] source code
* [[Semicolon]]s terminate [[Statement (programming)|statements]]
* [[Curly braces]] group statements into [[Block (programming)|blocks]]
* [[Executable code]] is contained in [[function]]s; no script-like syntax
* [[Function parameter|Parameters]] are passed by value; pass by-reference is achieved by passing a pointer to a value
* Relatively small number of keywords
* [[Control flow]] constructs, including <code>[[Conditional (computer programming)|if]]</code>, <code>[[For loop|for]]</code>, <code>[[Do while loop|do]]</code>, <code>[[While loop|while]]</code>, and <code>[[Switch statement|switch]]</code>
* [[Arithmetic]], [[bitwise]], and logic operators, including {{codes|+|+{{=}}|++|&amp;|{{!!}}|d=,}}
* Multiple [[Assignment (computer science)|assignments]] may be performed in a single statement
* User-defined identifiers are not distinguished from keywords; i.e. by a [[Sigil (computer programming)|sigil]]
* A variable declared inside a block is accessible only in that block and only below the declaration
* A function return value can be ignored
* A function cannot be nested inside a function; but some translators support this
* [[Run-time polymorphism]] may be achieved using function pointers
* Supports [[Recursion (computer science)|recursion]]
* Data typing is [[Static typing|static]], but [[Strong and weak typing|weakly enforced]]; all variables have a type, but [[implicit conversion]] between primitive types weakens the separation of the different types
* [[typedef|User-defined]] data types allow for aliasing a data type specifier
* Syntax for [[Array (data type)|array]] definition and access is via square bracket notation, for example <code>month[11]</code>. Indexing is defined in terms of pointer arithmetic. Whole arrays cannot be copied or compared without custom or library code
* User-defined [[struct (C programming language)|structure]] types allow related data elements to be passed and copied as a unit although two structures cannot be compared without custom code to compare each field
* User-defined [[Union type|union]] types support overlapping members; allowing multiple data types to share the same [[memory ___location]]
* User-defined [[enumerated type|enumeration]] types support aliasing integer values
* Lacks a [[String (computer science)|string type]] but has syntax for [[null-terminated string|null-terminated strings]] with associated [[C string handling|handling]] in its standard library
* Supports low-level access to [[computer memory]] via [[Pointer (computer programming)|pointers]]
* Supports [[Procedure (computer science)|procedure-like]] construct as a function returning <code>void</code>
* Supports [[Dynamic allocation|dynamic memory]] via standard library functions
* Includes the [[C preprocessor]] to perform [[Macro (computer science)|macro]] definition, [[source code]] file inclusion, and [[conditional compilation]]
* Supports [[Modular programming|modularity]] in that files are processed separately, with visibility control via <code>static</code> and <code>extern</code> attributes
* Minimized functionality in the core language while relatively complex functionality such as [[Input/output|I/O]], string manipulation, and mathematical functions supported via standard library functions
* Resulting compiled code has relatively straightforward needs on the underlying platform; making it desirable for operating and [[embedded system|embedded]] systems
{{Div col end}}
 
== <span class="anchor" id="HELLOWORLD"></span>"Hello, world" example ==
C program source text is [[Free-form language|free-form]] code. [[Semicolon]]s terminate [[Statement (programming)|statements]], while [[curly braces]] are used to group statements into [[Block (programming)|blocks]].
[[File:Hello World Brian Kernighan 1974.jpg|thumb|"Hello, World!" program by [[Brian Kernighan]] (1978)]]
The [["Hello, World!" program]] example that appeared in the first edition of ''[[The C Programming Language|K&R]]'' has become the model for an introductory program in most programming textbooks. The program prints "hello, world" to the [[standard output]].
 
The original version was:{{sfnp|Kernighan|Ritchie|1978|p=6}}
The C language also exhibits the following characteristics:
* The language has a small, fixed number of keywords, including a full set of [[control flow]] primitives: <code>[[Conditional (computer programming)|if/else]]</code>, <code>[[For loop|for]]</code>, <code>[[Do while loop|do/while]]</code>, <code>[[While loop|while]]</code>, and <code>[[Switch statement|switch]]</code>. User-defined names are not distinguished from keywords by any kind of [[Sigil (computer programming)|sigil]].
* It has a large number of arithmetic, [[bitwise]], and logic operators: {{codes|+|+{{=}}|++|&amp;|{{!!}}|d=,}}, etc.
* More than one [[Assignment (computer science)|assignment]] may be performed in a single statement.
* Functions:
** Function return values can be ignored, when not needed.
** Function and data pointers permit ''ad hoc'' [[run-time polymorphism]].
** Functions may not be defined within the lexical scope of other functions.
** Variables may be defined within a function, with [[lexical variable scope|scope]].
** A function may call itself, so [[Recursion (computer science)|recursion]] is supported.
* Data typing is [[Static typing|static]], but [[Strong and weak typing|weakly enforced]]; all data has a type, but [[implicit conversion]]s are possible.
* User-defined ([[typedef]]) and compound types are possible.
** Heterogeneous aggregate data types (<code>[[Struct (C programming language)|struct]]</code>) allow related data elements to be accessed and assigned as a unit. The contents of whole structs cannot be compared using a single built-in operator (the elements must be compared individually).
** [[Union type|Union]] is a structure with overlapping members; it allows multiple data types to share the same memory ___location.
** [[Array (data type)|Array]] indexing is a secondary notation, defined in terms of pointer arithmetic. Whole arrays cannot be assigned or compared using a single built-in operator. There is no "array" keyword in use or definition; instead, square brackets indicate arrays syntactically, for example <code>month[11]</code>.
** [[Enumerated type]]s are possible with the <code>enum</code> keyword. They are freely interconvertible with integers.
** [[String (computer science)|Strings]] are not a distinct data type, but are conventionally [[C string handling|implemented]] as [[Null-terminated string|null-terminated]] character arrays.
* Low-level access to [[computer memory]] is possible by converting machine addresses to [[Pointer (computer programming)|pointers]].
* [[Procedure (computer science)|Procedures]] (subroutines not returning values) are a special case of function, with an empty return type <code>void</code>.
* Memory can be [[Dynamic allocation|allocated]] to a program with calls to [[library routine]]s.
* A [[C preprocessor|preprocessor]] performs [[Macro (computer science)|macro]] definition, [[source code]] file inclusion, and [[conditional compilation]].
* There is a basic form of [[Modular programming|modularity]]: files can be compiled separately and [[Linker (computing)|linked]] together, with control over which functions and data objects are visible to other files via [[Static (keyword)|<code>static</code>]] and <code>extern</code> attributes.
* Complex functionality such as [[Input/output|I/O]], [[String (computer science)|string]] manipulation, and mathematical functions are consistently delegated to [[library routine]]s.
* The generated code after compilation has relatively straightforward needs on the underlying platform, which makes it suitable for creating operating systems and for use in [[embedded system]]s.
 
<syntaxhighlight lang="c">
While C does not include certain features found in other languages (such as [[Object-oriented programming|object orientation]] and [[garbage collection (computer science)|garbage collection]]), these can be implemented or emulated, often through the use of external libraries (e.g., the [[GLib Object System]] or the [[Boehm garbage collector]]).
main()
{
printf("hello, world\n");
}
</syntaxhighlight>
 
A more modern version is:{{efn|The original example code will compile on most modern compilers that are not in strict standard compliance mode, but it does not fully conform to the requirements of either C89 or C99. In fact, C99 requires that a diagnostic message be produced.}}
=== Relations to other languages ===
 
{{main|List of C-family programming languages}}
<!-- READ THIS BEFORE YOU EDIT! If you think there is a better way, first see talk page archive No. 8 for why. If you still want to change it, discuss it first.
Many later languages have borrowed directly or indirectly from C, including [[C++]], [[C Sharp (programming language)|C#]], Unix's [[C shell]], [[D (programming language)|D]], [[Go (programming language)|Go]], [[Java (programming language)|Java]], [[JavaScript]] (including [[JavaScript#transpilers|transpilers]]), [[Julia (programming language)|Julia]], [[Limbo (programming language)|Limbo]], [[LPC (programming language)|LPC]], [[Objective-C]], [[Perl]], [[PHP]], [[Python (programming language)|Python]], [[Ruby (programming language)|Ruby]], [[Rust (programming language)|Rust]], [[Swift (programming language)|Swift]], [[Verilog]] and [[SystemVerilog]] (hardware description languages).<ref name="vinsp" /> These languages have drawn many of their [[control structures]] and other basic features from C. Most of them also express highly similar [[Syntax (programming languages)|syntax]] to C, and they tend to combine the recognizable expression and statement [[C syntax|syntax of C]] with underlying type systems, [[data model]]s, and semantics that can be radically different.
-->
<syntaxhighlight lang="c">
#include <stdio.h>
 
int main(void)
{
printf("hello, world\n");
}
</syntaxhighlight>
 
The first line is a [[C preprocessor|preprocessor]] [[Directive (programming)|directive]], indicated by <code>#include</code>, which causes the preprocessor to replace that line of code with the text of the <code>[[stdio.h]]</code> header file, which contains declarations for input and output functions including <code>printf</code>. The angle brackets around <code>stdio.h</code> indicate that the header file can be located using a search strategy that selects header files provided with the compiler over files with the same name that may be found in project-specific directories.
 
The next code line declares the [[entry point]] function <code>main</code>. The [[run-time environment]] calls this function to begin program execution. The type specifier <code>int</code> indicates that the function returns an integer value. The <code>void</code> parameter list indicates that the function consumes no arguments. The run-time environment actually passes two arguments (typed <code>int</code> and <code>char *[]</code>), but this implementation ignores them. The ISO C standard (section 5.1.2.2.1) requires syntax that either is void or these two arguments{{snd}}a special treatment not afforded to other functions.
 
The opening curly brace indicates the beginning of the code that defines the function.
 
The next line of code calls (diverts execution to) the C standard library function <code>[[printf]]</code> with the [[Memory address|address]] of the first character of a null-terminated string specified as a [[string literal]]. The text <code>\n</code> is an [[escape sequence]] that denotes the [[newline]] character which when output in a terminal results in moving the cursor to the beginning of the next line. Even though <code>printf</code> returns an <code>int</code> value, it is silently discarded. The semicolon <code>;</code> terminates the call statement.
 
The closing curly brace indicates the end of the <code>main</code> function. Prior to C99, an explicit <code>return 0;</code> statement was required at the end of <code>main</code> function, but since C99, the <code>main</code> function (as being the initial function call) implicitly returns <code>0</code> upon reaching its final closing curly brace.{{efn|Return value <code>0</code> is typically used in this context to indicate success.<ref name="bk21st">{{cite book |last1=Klemens |first1=Ben |author-link=Ben Klemens |title=21st Century C |publisher=[[O'Reilly Media]] |year=2013 |isbn=978-1-4493-2714-9}}</ref>}}
 
== History ==
Line 121 ⟶ 153:
|}
 
The origin of C is closely tied to the development of the [[Unix]] operating system, originally implemented in [[assembly language]] on a [[PDP-7]] by [[Dennis Ritchie]] and [[Ken Thompson]], incorporating several ideas from colleagues. Eventually, they decided to port the operating system to a [[PDP-11]]. The original PDP-11 version of Unix was also developed in assembly language.<ref name="sigplan" />{{sfnp|Ritchie|1993a}}
 
==== B ====
{{main|B (programming language)}}
Thompson wanted a programming language for developing utilities for the new platform. He first tried writing a [[Fortran]] compiler, but he soon gave up the idea and instead created a cut-down version of the recently developed [[systems programming language]] called [[BCPL]]. The official description of BCPL was not available at the time,<ref name="NFDsZ">{{cite web |url=https://www.lysator.liu.se/c/dmr-on-histories.html |first=Dennis |last=Ritchie |title=BCPL to B to C |website=lysator.liu.se |access-date=September 10, 2019 |archive-date=December 12, 2019 |archive-url=https://web.archive.org/web/20191212221532/http://www.lysator.liu.se/c/dmr-on-histories.html |url-status=live }}</ref> and Thompson modified the syntax to be less 'wordy' and similar to a simplified [[ALGOL]] known as SMALGOL.<ref name="Ars">{{Cite web |last=Jensen |first=Richard |date=December 9, 2020 |title="A damn stupid thing to do"—the origins of C |url=https://arstechnica.com/features/2020/12/a-damn-stupid-thing-to-do-the-origins-of-c/ |access-date=March 28, 2022 |website=Ars Technica |language=en-us |archive-date=March 28, 2022 |archive-url=https://web.archive.org/web/20220328143845/https://arstechnica.com/features/2020/12/a-damn-stupid-thing-to-do-the-origins-of-c/ |url-status=live }}</ref> He called the result [[B (programming language)|''B'']],<ref name="sigplan" />{{sfnp|Ritchie|1993a}} describing it as "BCPL semantics with a lot of SMALGOL syntax".<ref name=Ars /> Like BCPL, B had a [[bootstrapping]] compiler to facilitate porting to new machines.<ref name=Ars /> Ultimately, few utilities were written in B because it was too slow and could not take advantage of PDP-11 features such as [[byte]] addressability.
 
Unlike BCPL's <code>// comment</code> marking comments up to the end of the line, B adopted <code>/* comment */</code> as the comment delimiter, more akin to PL/1, and allowing comments to appear in the middle of lines. (BCPL's comment style would be reintroduced in C++.){{sfnp|Ritchie|1993a}}
 
==== New B and first C release ====
In 1971 Ritchie started to improve B, to use the features of the more-powerful PDP-11. A significant addition was a character data type. He called this ''New B'' (NB).<ref name=Ars /> Thompson started to use NB to write the [[Research Unix|Unix]] kernel, and his requirements shaped the direction of the language development.<ref name="Ars" /><ref name="unixport" />

Through to 1972, richer types were added to the NB language:. NB had arrays of <code>int</code> and <code>char</code>., Pointersand to these types were added pointers, the ability to generate pointers to other types, arrays of all types, and types to be returned from functions were all also added. Arrays within expressions becamewere effectively treated as pointers. A new compiler was written, and the language was renamed C.<ref name=sigplan />{{sfnp|Ritchie|1993a}}
 
The C compiler and some utilities made with it were included in [[Version 2 Unix]], which is also known as [[Research Unix]].<ref name="QtqTh">{{cite tech report |first=M. D. |last=McIlroy |author-link=Doug McIlroy |year=1987 |url=http://www.cs.dartmouth.edu/~doug/reader.pdf |title=A Research Unix reader: annotated excerpts from the Programmer's Manual, 1971–1986 |series=CSTR |number=139 |institution=Bell Labs |format=PDF |page=10 |access-date=February 1, 2015 |archive-date=November 11, 2017 |archive-url=https://web.archive.org/web/20171111151817/http://www.cs.dartmouth.edu/~doug/reader.pdf |url-status=live }}</ref>
 
==== Structures and Unix kernel re-write ====
At [[Version 4 Unix]], released in November 1973, the [[Unix]] [[kernel (operating system)|kernel]] was extensively re-implemented in C.<ref name="sigplan" />{{sfnp|Ritchie|1993a}} By this time, the C language had acquired some powerful features such as <code>struct</code> types.
 
The [[C preprocessor|preprocessor]] was introduced around 1973 at the urging of [[Alan Snyder (computer scientist)|Alan Snyder]] and also in recognition of the usefulness of the file-inclusion mechanisms available in BCPL and [[PL/I]]. Its original version provided only included files and simple string replacements: <code>#include</code> and <code>#define</code> of parameterless macros. Soon after that, it was extended, mostly by [[Mike Lesk]] and then by John Reiser, to incorporate macros with arguments and [[conditional compilation]].<ref name="sigplan">{{harvtxtsfnp|Ritchie|19931993a}}</ref>
 
Unix was one of the first operating system kernels implemented in a language other than [[assembly language|assembly]]. Earlier instances include the [[Multics]] system (which was written in [[PL/I]]) and [[Master Control Program]] (MCP) for the [[Burroughs large systems|Burroughs B5000]] (which was written in [[ALGOL]]) in 1961. In around <!--Better?: {{Circa|1977}}--> 1977, Ritchie and [[Stephen C. Johnson]] made further changes to the language to facilitate [[Software portability|portability]] of the Unix operating system. Johnson's [[Portable C Compiler]] served as the basis for several implementations of C on new platforms.<ref name="unixport">{{cite journal |last1=Johnson |first1=S. C. |author-link1=Stephen C. Johnson |last2=Ritchie |first2=D. M. |author-link2=Dennis Ritchie |title=Portability of C Programs and the UNIX System |journal=Bell System Tech. J. |year=1978 |volume=57 |issue=6 |pages=2021–2048 |doi=10.1002/j.1538-7305.1978.tb02141.x |citeseerx=10.1.1.138.35 |s2cid=17510065 |issn = 0005-8580 }} (Note: The PDF is an OCR scan of the original, and contains a rendering of "IBM 370" as "IBM 310".)</ref>
Line 141 ⟶ 177:
=== K&R C ===<!--[[K&R C]] redirects here-->
[[File:The C Programming Language, First Edition Cover (2).svg|thumb|240x240px|The cover of the book ''The C Programming Language'', first edition, by [[Brian Kernighan]] and [[Dennis Ritchie]]]]
In 1978 [[Brian Kernighan]] and [[Dennis Ritchie]] published the first edition of ''[[The C Programming Language]]''.<ref name="k&r1e">{{cite book sfnp|last1=Kernighan |first1=Brian W. |author-link1=Brian Kernighan |last2=Ritchie |first2=Dennis M. |author-link2=Dennis Ritchie | title=The C Programming Language | edition=1st |publisher=[[Prentice Hall]] |date=February 1978 |___location=[[Englewood Cliffs, NJ]] |isbn=978-0-13-110163-0|title-link=The C Programming Language}}</ref> Known as ''K&R'' from the initials of its authors, the book served for many years as an informal [[Specification (technical standard)|specification]] of the language. The version of C that it describes is commonly referred to as "'''K&R C'''<!--boldface per WP:R#PLA-->". As this was released in 1978, it is now also referred to as ''C78''.<ref name="qOvzA">{{cite book |url=https://nxmnpg.lemoda.net/7/c78 |title=FreeBSD Miscellaneous Information Manual |date=May 30, 2011 |edition=FreeBSD 13.0 |chapter=C manual pages |access-date=January 15, 2021 |archive-url=https://web.archive.org/web/20210121024455/https://nxmnpg.lemoda.net/7/c78 |archive-date=January 21, 2021 |url-status=live}} [https://www.freebsd.org/cgi/man.cgi?query=c78&apropos=0&sektion=0&manpath=FreeBSD+9-current&arch=default&format=html] {{Webarchive|url=https://web.archive.org/web/20210121033654/https://www.freebsd.org/cgi/man.cgi?query=c78&apropos=0&sektion=0&manpath=FreeBSD+9-current&arch=default&format=html|date=January 21, 2021}}</ref> The second edition of the book<ref name="k&r2e">{{cite book sfnp|last1=Kernighan |first1=Brian W. |author-link1=Brian Kernighan |last2=Ritchie |first2=Dennis M. |author-link2=Dennis Ritchie |title=The C Programming Language | edition=2nd |publisher=[[Prentice Hall]] |date=March 1988 |___location=[[Englewood Cliffs, NJ]] |isbn=978-0-13-110362-7|title-link=The C Programming Language |ref=none}}</ref> covers the later [[ANSI C]] standard, described below.
 
''K&R'' introduced several language features:
Line 151 ⟶ 187:
Even after the publication of the 1989 ANSI standard, for many years K&R C was still considered the "[[Lowest common denominator (computers)|lowest common denominator]]" to which C programmers restricted themselves when maximum portability was desired, since many older compilers were still in use, and because carefully written K&R C code can be legal Standard C as well.
 
InAlthough earlylater versions of C require functions to have an explicit type declaration, K&R C only requires functions that return typesa type other than <code>int</code> mustto be declared if used before theuse. function definition; functionsFunctions used without prior declaration were presumed to return type <code>int</code>.
 
For example:
 
<syntaxhighlight lang="c" line>
long long_function();
long some_function(); /* This is a function declaration, so the compiler can know the name and return type of this function. */
/* int */ other_function(); /* Another function declaration. Because this is an early version of C, there is an implicit 'int' type here. A comment shows where the explicit 'int' type specifier would be required in later versions. */
 
calling_function()
/* int */ calling_function() /* This is a function definition, including the body of the code following in the { curly brackets }. Because no return type is specified, the function implicitly returns an 'int' in this early version of C. */
{
long test1longvar;
register intvar;
register /* int */ test2; /* Again, note that 'int' is not required here. The 'int' type specifier */
longvar = long_function();
/* in the comment would be required in later versions of C. */
if (longvar > 1)
/* The 'register' keyword indicates to the compiler that this variable should */
intvar = 0;
/* ideally be stored in a register as opposed to within the stack frame. */
test1 = some_function();
if (test1 > 1)
test2 = 0;
else
test2intvar = other_functionint_function();
return test2intvar;
}
</syntaxhighlight>
 
The declaration of {{code|long_function()}} (on line 1) is required since it returns {{code|long}}; not {{code|int}}. Function {{code|int_function}} can be called (line 11) even though it is not declared since it returns {{code|int}}. Also, variable {{code|intvar}} does not need to be declared as type {{code|int}} since that is the default type for {{code|register}} keyword.
The <code>int</code> type specifiers which are commented out could be omitted in K&R C, but are required in later standards.
 
Since K&R function declarations did not include any information about function arguments, function parameter [[Type checking|type checks]] were not performed, although some compilers would issue a warning message if a local function was called with the wrong number of arguments, or if different calls to an externala function used different numbers or types of arguments. Separate toolsTools such as Unix's [[Lint programming tool|lint]] utility were developed that (among other things) could checkchecked for consistency of function use across multiple source files.
 
In the years following the publication of K&R C, several features were added to the language, supported by compilers from AT&T (in particular [[Portable C Compiler|PCC]]<ref name="SkKfZ">{{cite report |first1=Bjarne |last1=Stroustrup |author-link=Bjarne Stroustrup |title=Sibling rivalry: C and C++ |publisher=AT&T Labs |number=TD-54MQZY |year=2002 |url=http://stroustrup.com/sibling_rivalry.pdf |access-date=April 14, 2014 |archive-date=August 24, 2014 |archive-url=https://web.archive.org/web/20140824072719/http://www.stroustrup.com/sibling_rivalry.pdf |url-status=live }}</ref>) and some other vendors. These included:
* <code>[[void type|void]]</code> functions (i.e.,; functions withreturning no return value)
* functionsFunctions returning <code>[[Struct (C programming language)|struct]]</code> or <code>[[Union (computer science)|union]]</code> types (previously only a single pointer, integer or float could be returned)
* [[Assignment (computer science)|assignmentAssignment]] for <code>struct</code> data typesvariables
* [[Enumerated type]]s
* [[enumerated type]]s (previously, preprocessor definitions for integer fixed values were used, e.g. <code>#define GREEN 3</code>)
 
The large numberpopularity of extensionsthe andlanguage, lack of agreement on a [[C standard library|standard library]] interfaces, together with the language popularity and thelack factof thatcompliance not even the Unix compilers precisely implementedto the K&R specification, ledlead to thestandardization necessity of standardizationefforts.<ref>{{Cite web |url=https://www.cs.man.ac.uk/~pjj/cs211/c_rationale/node2.html |title=Rationale for American National Standard for Information Systems – Programming Language – C |access-date=July 17, 2024 |archive-url=https://web.archive.org/web/20240717164722/https://www.cs.man.ac.uk/~pjj/cs211/c_rationale/node2.html |archive-date=July 17, 2024}}</ref>
 
=== ANSI C and ISO C ===
Line 193 ⟶ 225:
During the late 1970s and 1980s, versions of C were implemented for a wide variety of [[mainframe computer]]s, [[minicomputer]]s, and [[microcomputer]]s, including the [[IBM PC]], as its popularity began to increase significantly.
 
In 1983 the [[American National Standards Institute]] (ANSI) formed a committee, X3J11, to establish a standard specification of C. X3J11 based the C standard on the Unix implementation; however, the non-portable portion of the Unix C library was handed off to the [[IEEE]] [[working group]] 1003 to become the basis for the 1988 [[POSIX]] standard. In 1989, the C standard was ratified as ANSI X3.159-1989 "Programming Language C". This version of the language is often referred to as [[ANSI C]], Standard C, or sometimes '''C89'''.
 
In 1990 the ANSI C standard (with formatting changes) was adopted by the [[International Organization for Standardization]] (ISO) as ISO/IEC 9899:1990, which is sometimes called '''C90'''. Therefore, the terms "C89" and "C90" refer to the same programming language.
 
ANSI, like other national standards bodies, no longer develops the C standard independently, but defers to the international C standard, maintained by the working group [[ISO/IEC JTC1/SC22]]/WG14. National adoption of an update to the international standard typically occurs within a year of ISO publication.
Line 233 ⟶ 265:
{{Main|C23 (C standard revision)}}
 
C23 is an informal name for the current major C language standard revision. Itand was informally known as "C2X" through most of its development. It builds on past releases, introducing features like new keywords, types including <code>nullptr_t</code> and <code>_BitInt(N)</code>, and expansions to the standard library.<ref>{{cite web |title=ISO/IEC 9899:2024 (en) — N3220 working draft |url=https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3220.pdf |access-date=11 July 2025}}</ref>

C23 was published in October 2024 as ISO/IEC 9899:2024.<ref name="N3132">{{cite web |title=WG14-N3132 : Revised C23 Schedule |url=https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3132.pdf |website=open-std.org |archive-url=https://web.archive.org/web/20230609204739/https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3132.pdf |archive-date=June 9, 2023 |date=June 4, 2023 |url-status=live}}</ref> The standard macro <code>__STDC_VERSION__</code> is defined as <code>202311L</code> to indicate that C23 support is available.
 
=== C2Y ===
C2Y is an informal name for the next major C language standard revision, after C23 (C2X), that is hoped to be released later in the 2020s decade, hence the '2' in "C2Y". An early working draft of C2Y was released in February 2024 as N3220 by the working group [[ISO/IEC JTC1/SC22]]/WG14.<ref name="N3220">{{cite web |title=WG14-N3220 : Working Draft, C2y |url=https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3220.pdf |website=open-std.org |archive-url=https://web.archive.org/web/20240226053735/https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3220.pdf |archive-date=February 26, 2024 |date=February 21, 2024 |url-status=live}}</ref>
 
=== Embedded C ===
Line 245 ⟶ 279:
In 2008, the C Standards Committee published a [[technical report]] extending the C language<ref name="TR18037">{{cite web |title=TR 18037: Embedded C |url=https://www.open-std.org/jtc1/sc22/wg14/www/docs/n1169.pdf |website=open-std.org |id=ISO/IEC JTC1 SC22 WG14 N1169 |date=April 4, 2006 |access-date=July 26, 2011 |archive-date=February 25, 2021 |archive-url=https://web.archive.org/web/20210225224616/https://www.open-std.org/jtc1/sc22/wg14/www/docs/n1169.pdf |url-status=live }}</ref> to address these issues by providing a common standard for all implementations to adhere to. It includes a number of features not available in normal C, such as fixed-point arithmetic, named address spaces, and basic I/O hardware addressing.
 
== SyntaxDefinition ==
{{Main|C syntax}}
 
Line 266 ⟶ 300:
 
The ''newline'' character indicates the end of a text line; it need not correspond to an actual single character, although for convenience C treats it as such.
 
The POSIX standard mandates a [[portable character set]] which adds a few characters (notably "@") to the basic C source character set. Both standards do not prescribe any particular value encoding -- ASCII and [[EBCDIC]] both comply with these standards, since they include at least those basic characters, even though they use different encoded values for those characters.
 
Additional multi-byte encoded characters may be used in [[string literal]]s, but they are not entirely [[Software portability|portable]]. Since [[C99]] multi-national Unicode characters can be embedded portably within C source text by using <code>\uXXXX</code> or <code>\UXXXXXXXX</code> encoding (where <code>X</code> denotes a hexadecimal character).
Line 272 ⟶ 308:
 
=== Reserved words ===
TheAll followingversions of C have [[reserved words]] that are [[case sensitive]]. As reserved words, they cannot be used for variable names.
 
C89 has 32 reserved words:
C89 has 32 reserved words, also known as 'keywords', which cannot be used for any purposes other than those for which they are predefined:
 
{{div col|colwidth=13em}}
Line 384 ⟶ 420:
The C [[operator precedence]] is not always intuitive. For example, the operator <code>==</code> binds more tightly than (is executed prior to) the operators <code>&</code> (bitwise AND) and <code>|</code> (bitwise OR) in expressions such as <code>x & 1 == 0</code>, which must be written as <code>(x & 1) == 0</code> if that is the coder's intent.<ref name="AutoTX-9">{{cite book |title=C and the 8051 |edition=3rd |last1=Schultz |first1=Thomas |year=2004 |publisher=PageFree Publishing Inc. |___location=Otsego, MI |isbn=978-1-58961-237-2 |page=20 |url={{GBurl|id=rI0c8kWbxooC|pg=PT47}} |access-date=February 10, 2012 }}</ref>
 
=== Data types ===
== <span class="anchor" id="HELLOWORLD"></span>"Hello, world" example ==
{{See also|"Hello, World!" program}}
[[File:Hello World Brian Kernighan 1974.jpg|thumb|"Hello, World!" program by [[Brian Kernighan]] (1978)]]
The "hello, world" example that appeared in the first edition of ''[[The C Programming Language|K&R]]'' has become the model for an introductory program in most programming textbooks. The program prints "hello, world" to the [[standard output]], which is usually a terminal or screen display.
 
The original version was:{{sfnp|Kernighan|Ritchie|1978|p=6}}
 
<syntaxhighlight lang="c">
main()
{
printf("hello, world\n");
}
</syntaxhighlight>
 
A standard-conforming "hello, world" program is:{{efn|The original example code will compile on most modern compilers that are not in strict standard compliance mode, but it does not fully conform to the requirements of either C89 or C99. In fact, C99 requires that a diagnostic message be produced.}}
 
<!-- READ THIS BEFORE YOU EDIT! If you think there is a better way, first see talk page archive No. 8 for why. If you still want to change it, discuss it first.
-->
<syntaxhighlight lang="c">
#include <stdio.h>
 
int main(void)
{
printf("hello, world\n");
}
</syntaxhighlight>
 
The first line of the program contains a [[preprocessing directive]], indicated by <code>#include</code>. This causes the compiler to replace that line of code with the entire text of the <code>[[stdio.h]]</code> header file, which contains declarations for standard input and output functions such as <code>printf</code> and <code>scanf</code>. The angle brackets surrounding <code>stdio.h</code> indicate that the header file can be located using a search strategy that prefers headers provided with the compiler to other headers having the same name (as opposed to double quotes which typically include local or project-specific header files).
 
The second line indicates that a function named <code>main</code> is being defined. The <code>[[Entry point|main]]</code> function serves a special purpose in C programs; the [[run-time environment]] calls the <code>main</code> function to begin program execution. The type specifier <code>int</code> indicates that the value returned to the invoker (in this case the run-time environment) as a result of evaluating the <code>main</code> function, is an integer. The keyword <code>void</code> as a parameter list indicates that the <code>main</code> function takes no arguments.{{efn|The <code>main</code> function actually has two arguments, <code>int argc</code> and <code>char *argv[]</code>, respectively, which can be used to handle [[command-line argument]]s. The ISO C standard (section 5.1.2.2.1) requires both forms of <code>main</code> to be supported, which is special treatment not afforded to any other function.}}
 
The opening curly brace indicates the beginning of the code that defines the <code>main</code> function.
 
The next line of the program is a statement that ''calls'' (i.e. diverts execution to) a function named <code>[[printf]]</code>, which in this case is supplied from a system [[Library (computing)|library]]. In this call, the <code>printf</code> function is ''passed'' (i.e. provided with) a single argument, which is the [[Memory address|address]] of the first character in the [[string literal]] <code>"hello, world\n"</code>. The string literal is an unnamed [[Array (data type)|array]] set up automatically by the compiler, with elements of type <code>char</code> and a final [[Null character|NULL character]] (ASCII value 0) marking the end of the array (to allow <code>printf</code> to determine the length of the string). The NULL character can also be written as the [[Escape sequences in C|escape sequence]] <code>\0</code>. The <code>\n</code> is a standard escape sequence that C translates to a ''[[newline]]'' character, which, on output, signifies the end of the current line. The return value of the <code>printf</code> function is of type <code>int</code>, but it is silently discarded since it is not used. (A more careful program might test the return value to check that the <code>printf</code> function succeeded.) The semicolon <code>;</code> terminates the statement.
 
The closing curly brace indicates the end of the code for the <code>main</code> function. According to the C99 specification and newer, the <code>main</code> function (unlike any other function) will implicitly return a value of <code>0</code> upon reaching the <code>}</code> that terminates the function.{{efn|Prior to C99, an explicit <code>return 0;</code> statement was required at the end of the <code>main</code> function.}} The return value of <code>0</code> is interpreted by the run-time system as an exit code indicating successful execution of the function.<ref name="bk21st">{{cite book |last1=Klemens |first1=Ben |author-link=Ben Klemens |title=21st Century C |publisher=[[O'Reilly Media]] |year=2013 |isbn=978-1-4493-2714-9}}</ref>
 
== Data types ==
{{Main|C data types}}
{{More citations needed section|date=October 2012}}
Line 434 ⟶ 433:
C's ''usual arithmetic conversions'' allow for efficient code to be generated, but can sometimes produce unexpected results. For example, a comparison of signed and unsigned integers of equal width requires a conversion of the signed value to unsigned. This can generate unexpected results if the signed value is negative.
 
==== Pointers ====
C supports the use of [[Pointer (computer programming)|pointers]], a type of [[Reference (computer science)|reference]] that records the address or ___location of an object or function in memory. Pointers can be ''dereferenced'' to access data stored at the address pointed to, or to invoke a pointed-to function. Pointers can be manipulated using assignment or [[pointer arithmetic]]. The run-time representation of a pointer value is typically a raw memory address (perhaps augmented by an offset-within-word field), but since a pointer's type includes the type of the thing pointed to, expressions including pointers can be type-checked at compile time. Pointer arithmetic is automatically scaled by the size of the pointed-to data type.
 
Line 445 ⟶ 444:
Careless use of pointers is potentially dangerous. Because they are typically unchecked, a pointer variable can be made to point to any arbitrary ___location, which can cause undesirable effects. Although properly used pointers point to safe places, they can be made to point to unsafe places by using invalid [[pointer arithmetic]]; the objects they point to may continue to be used after deallocation ([[dangling pointer]]s); they may be used without having been initialized ([[wild pointer]]s); or they may be directly assigned an unsafe value using a cast, union, or through another corrupt pointer. In general, C is permissive in allowing manipulation of and conversion between pointer types, although compilers typically provide options for various levels of checking. Some other programming languages address these problems by using more restrictive [[Reference (computer science)|reference]] types.
 
==== Arrays ====
{{See also|C string handling}}
<!-- Please be careful when editing this. C does *not* forbid bounds checking, nor does it require that pointers are memory addresses. Of course it does not require bounds checks, either, and all common implementations map those language constructs to the machine in an "obvious way", but there are ANSI-conforming implementations that handle these things in other ways. -->
Line 486 ⟶ 485:
</syntaxhighlight>
 
==== Array–pointer interchangeability ====
The subscript notation <code>x[i]</code> (where <code>x</code> designates a pointer) is [[syntactic sugar]] for <code>*(x+i)</code>.<ref name="Raymond1996">{{cite book |last1=Raymond |first1=Eric S. |author-link=Eric S. Raymond |title=The New Hacker's Dictionary |edition=3rd |url={{GBurl|id=g80P_4v4QbIC|p=432}} |access-date=August 5, 2012 |date=October 11, 1996 |publisher=MIT Press |isbn=978-0-262-68092-9 |page=432 }}</ref> Taking advantage of the compiler's knowledge of the pointer type, the address that <code>x + i</code> points to is not the base address (pointed to by <code>x</code>) incremented by <code>i</code> bytes, but rather is defined to be the base address incremented by <code>i</code> multiplied by the size of an element that <code>x</code> points to. Thus, <code>x[i]</code> designates the <code>i+1</code>th element of the array.
 
Line 493 ⟶ 492:
The total size of an array <code>x</code> can be determined by applying <code>sizeof</code> to an expression of array type. The size of an element can be determined by applying the operator <code>sizeof</code> to any dereferenced element of an array <code>A</code>, as in <code>n = sizeof A[0]</code>. Thus, the number of elements in a declared array <code>A</code> can be determined as <code>sizeof A / sizeof A[0]</code>. Note, that if only a pointer to the first element is available as it is often the case in C code because of the automatic conversion described above, the information about the full type of the array and its length are lost.
 
=== Memory management ===
One of the most important functions of a programming language is to provide facilities for managing [[Computer memory|memory]] and the objects that are stored in memory. C provides three principal ways to allocate memory for objects:<ref name="bk21st" />
* [[Static memory allocation]]: space for the object is provided in the binary at compile-time; these objects have an [[Variable (programming)#Scope and extent|extent]] (or lifetime) as long as the binary which contains them is loaded into memory.
Line 507 ⟶ 506:
Heap memory allocation has to be synchronized with its actual usage in any program to be reused as much as possible. For example, if the only pointer to a heap memory allocation goes out of scope or has its value overwritten before it is deallocated explicitly, then that memory cannot be recovered for later reuse and is essentially lost to the program, a phenomenon known as a ''[[memory leak]].'' Conversely, it is possible for memory to be freed, but is referenced subsequently, leading to unpredictable results. Typically, the failure symptoms appear in a portion of the program unrelated to the code that causes the error, making it difficult to diagnose the failure. Such issues are ameliorated in languages with [[automatic garbage collection]].
 
=== Libraries ===
The C programming language uses [[Library (computing)|libraries]] as its primary method of extension. In C, a library is a set of functions contained within a single "archive" file. Each library typically has a [[header file]], which contains the prototypes of the functions contained within the library that may be used by a program, and declarations of special data types and macro symbols used with these functions. For a program to use a library, it must include the library's header file, and the library must be linked with the program, which in many cases requires [[compiler flag]]s (e.g., <code>-lm</code>, shorthand for "link the math library").<ref name="bk21st" />
 
Line 516 ⟶ 515:
Since many programs have been written in C, there are a wide variety of other libraries available. Libraries are often written in C because C compilers generate efficient [[object code]]; programmers then create interfaces to the library so that the routines can be used from higher-level languages like [[Java (programming language)|Java]], [[Perl]], and [[Python (programming language)|Python]].<ref name="bk21st" />
 
==== File handling and streams ====
File input and output (I/O) is not part of the C language itself but instead is handled by libraries (such as the C standard library) and their associated header files (e.g. <code>stdio.h</code>). File handling is generally implemented through high-level I/O which works through [[Stream (computing)|streams]]. A stream is from this perspective a data flow that is independent of devices, while a file is a concrete device. The high-level I/O is done through the association of a stream to a file. In the C standard library, a [[data buffer|buffer]] (a memory area or queue) is temporarily used to store data before it is sent to the final destination. This reduces the time spent waiting for slower devices, for example a [[hard drive]] or [[solid-state drive]]. Low-level I/O functions are not part of the standard C library{{clarify|date=October 2021}} but are generally part of "bare metal" programming (programming that is independent of any [[operating system]] such as most [[embedded programming]]). With few exceptions, implementations include low-level I/O.
 
== Language tools ==
{{More citations needed section|date=July 2014}}
 
A number of tools have been developed to help C programmers find and fix statements with undefined behavior or possibly erroneous expressions, with greater rigor than that provided by the compiler.
Line 539 ⟶ 537:
* With its rich set of operators, the C language can use many of the features of target CPUs. Where a particular CPU has more esoteric instructions, a language variant can be constructed with perhaps [[intrinsic function]]s 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.
Line 545 ⟶ 543:
* 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 convention]]s 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 is 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.
 
===Used for computationally-intensive libraries===
Line 551 ⟶ 549:
 
===Games===
Computer games are often built from a combination of languages. C has featured significantly, especially for those games attempting to obtain best performance from computer platforms. Examples include Doom from 1993.<ref>{{cite web |title=Development of Doom |url=https://doomwiki.org/wiki/Development_of_Doom |website=DoomWiki.org |access-date=2025-03-02 |language=en |date=2 March 2025}}</ref>
 
===C as an intermediate language===
Line 569 ⟶ 567:
 
==Limitations==
{{Rquote|quote=theRitchie powerhimself ofjoked assembly language andabout the conveniencelimitations of ... assemblythe language |author=Dennisthat Ritchiehe created:<ref>{{cite magazine |last1last=Metz |first1first=Cade |date=2011-10-13 |title=Dennis Ritchie: The Shoulders Steve Jobs Stood On |url=https://www.wired.com/2011/10/thedennisritchieeffect/ |url-access=subscription |magazine=Wired |access-date=April 19, 2022 |archive-date=April 12, 2022 |archive-url=https://web.archive.org/web/20220412005125/http://www.wired.com/2011/10/thedennisritchieeffect/ |url-status=live }}</ref>}}
{{blockquote |text=the power of assembly language and the convenience of ... assembly language |author=Dennis Ritchie}}
While C has been popular, influential and hugely successful, it has drawbacks, including:
While C is popular, influential and hugely successful, it has drawbacks, including:
* The standard [[dynamic memory]] handling with <code>malloc</code> and <code>free</code> is error prone. Improper use can lead to [[memory leaks]] and [[dangling pointers]].<ref>{{cite web |last1=Group |first1=Internet Security Research |title=What is memory safety and why does it matter? |url=https://www.memorysafety.org/docs/memory-safety/ |website=Prossimo |access-date=2025-03-03}}</ref>
* The standard [[dynamic memory]] handling with <code>malloc</code> and <code>free</code> is prone to mistakes. Improper use can lead to [[memory leaks]] and [[dangling pointers]].<ref>{{cite web |author=Internet Security Research Group |title=What is memory safety and why does it matter? |url=https://www.memorysafety.org/docs/memory-safety/ |website=Prossimo |access-date=March 3, 2025}}</ref>
* The use of pointers and the direct manipulation of memory means corruption of memory is possible, perhaps due to programmer error, or insufficient checking of bad data.
* The use of pointers and the direct manipulation of memory means corruption of memory is possible.
* There is some [[type checking]], but it does not apply to areas like [[variadic functions]], and the type checking can be trivially or inadvertently circumvented. It is [[Strong and weak typing|weakly typed]].
* There is [[type checking]], yet it does not apply to some areas like [[variadic functions]], and the type checking can be trivially or inadvertently circumvented. It is [[Strong and weak typing|weakly typed]], despite being statically typed.
* Since the code generated by the compiler contains few checks itself, there is a burden on the programmer to consider all possible outcomes, to protect against buffer overruns, array bounds checking, [[stack overflow]]s, memory exhaustion, and consider [[Race condition#In software|race conditions]], thread isolation, etc.
* Since the code generated by the compiler contains few runtime checks, there is a burden on the programmer to consider all possible outcomes, to protect against buffer overruns, array bounds checking, [[stack overflow]]s, memory exhaustion, and consider [[Race condition#In software|race conditions]], thread isolation, etc.
* The use of pointers and the run-time manipulation of these means there may be two ways to access the same data (aliasing), which is not determinable at compile time. This means that some optimisations that may be available to other languages are not possible in C. FORTRAN is considered faster.
* The use of pointers and the run-time manipulation of these enables there to be two ways to access the same data (aliasing), which is not always determinable at compile time. This means that some optimizations that may be available to some other languages, such as Fortran are not possible in C. For this reason, Fortran is sometimes considered faster. {{cn|date=August 2025}}
* Some of the standard library functions, e.g. <code>scanf</code> or {{code|strncat}}, can lead to [[C standard library#Buffer overflow vulnerabilities|buffer overruns]].
* There is limited standardisationstandardization in support for low-level variants in generated code, for example: different function [[calling conventions]] and [[Application binary interface|ABI]]; different [[Data structure alignment|structure packing]] conventions; different byte ordering within larger integers (including endianness). In many language implementations, some of these options may be handled with the preprocessor directive <code>[[C preprocessor#Compiler-specific preprocessor features|#pragma]]</code>,<ref>{{Cite web |last=corob-msft |title=Pragma directives and the __pragma and _Pragma keywords |url=https://learn.microsoft.com/en-us/cpp/preprocessor/pragma-directives-and-the-pragma-keyword |access-date=September 24, 2022 |website=Microsoft Learn |date=March 31, 2022 |language=en-us |archive-date=September 24, 2022 |archive-url=https://web.archive.org/web/20220924075131/https://learn.microsoft.com/en-us/cpp/preprocessor/pragma-directives-and-the-pragma-keyword |url-status=live }}</ref><ref>{{Cite web |title=Pragmas (The C Preprocessor) |url=https://gcc.gnu.org/onlinedocs/cpp/Pragmas.html |access-date=September 24, 2022 |website=GCC, the GNU Compiler Collection |archive-date=June 17, 2002 |archive-url=https://web.archive.org/web/20020617041757/https://gcc.gnu.org/onlinedocs/cpp/Pragmas.html |url-status=live }}</ref> and some with additional keywords e.g. use <code>[[__cdecl]]</code> calling convention. The directive and options are not consistently supported.<ref>{{cite web |title=Pragmas |url=https://www.intel.com/content/www/us/en/develop/documentation/cpp-compiler-developer-guide-and-reference/top/compiler-reference/pragmas.html |publisher=Intel |work=Intel C++ Compiler Classic Developer Guide and Reference |access-date=April 10, 2022 |language=en |archive-date=April 10, 2022 |archive-url=https://web.archive.org/web/20220410113529/https://www.intel.com/content/www/us/en/develop/documentation/cpp-compiler-developer-guide-and-reference/top/compiler-reference/pragmas.html |url-status=live }}</ref>
* [[C string handling|String handling]] using the standard library is code-intensive, with explicit memory management required.
* The language does not directly support object orientation, [[type introspection|introspection]], run-time expression evaluation (like eval in JS), genericsgarbage collection, etc.
* There are few guards against inappropriate usemisuse of language features, which may lead toenable [[Software maintenance|unmaintainable]] code. In particular, the [[C preprocessor]] can hide troubling effects such as double evaluation and worse.<ref>{{cite web |title=In praise of the C preprocessor |url=https://apenwarr.ca/log/20070813 |website=apenwarr |date=August 13, 2007 |access-date=July 9, 2023}}</ref> This facilitycapability for trickyobfuscated code has been celebrated with competitions such as the ''[[International Obfuscated C Code Contest]]'' and the ''[[Underhanded C Contest]]''.
* C lacks standard support for [[exception handling]] and only offers [[return code]]s for error checking. The [[Setjmp.h|<code>setjmp</code> and <code>longjmp</code>]] standard library functions have been used<ref>{{cite web|last1=Roberts |first1=Eric S. |title=Implementing Exceptions in C |date=March 21, 1989 |url=http://bitsavers.informatik.uni-stuttgart.de/pdf/dec/tech_reports/SRC-RR-40.pdf |archive-url=https://web.archive.org/web/20170115152453/http://bitsavers.informatik.uni-stuttgart.de/pdf/dec/tech_reports/SRC-RR-40.pdf |archive-date=January 15, 2017 |url-status=live |access-date=January 4, 2022 |publisher=[[DEC Systems Research Center]] |id=SRC-RR-40}}</ref> to implement a try-catch mechanism via macros. Also, goto statements are commmonly used for error handling. {{cn|date=August 2025}}
 
For some purposes, restricted styles of C have been adopted, e.g. [[MISRA C]] or [[CERT C]], in an attempt to reduce the opportunity for bugsglitches. Databases such as [[Common Weakness Enumeration|CWE]] attempt to count the ways that C etc. has potential vulnerabilities, along with recommendations for mitigation.
 
There are [[#Language tools|tools]] that can mitigate against some of the drawbacks. Contemporary C compilers include checks which may generate warnings to help identify many potential bugs.
 
== Related languages ==
 
[[File:Tiobe index 2020 may.png|alt=|thumb|The [[TIOBE index]]
[[File:Tiobe index 2020 may.png|alt=|thumb|The [[TIOBE index]] graph, showing a comparison of the popularity of various programming languages<ref name="MmjNC">{{cite magazine |url=https://www.wired.com/2013/01/java-no-longer-a-favorite/ |title=Is Java Losing Its Mojo? |first1=Robert |last1=McMillan |date=August 1, 2013 |magazine=[[Wired (magazine)|Wired]] |access-date=March 5, 2017 |archive-date=February 15, 2017 |archive-url=https://web.archive.org/web/20170215115409/https://www.wired.com/2013/01/java-no-longer-a-favorite/ |url-status=live }}</ref>]]
 
{{main|List of C-family programming languages}}
 
C has both directly and indirectly influenced many later languages such as [[C++]] and [[Java (programming language)|Java]].<ref name="kafmy">{{Cite book|title=Pillars of computing : a compendium of select, pivotal technology firms |last1=O'Regan |first1=Gerard |isbn=978-3319214641 |oclc=922324121 |date=September 24, 2015|publisher=Springer }}</ref> The most pervasive influence has been syntactical; all of the languages mentioned combine the statement and (more or less recognizably) expression [[C syntax|syntax of C]] with type systems, data models or large-scale program structures that differ from those of C, sometimes radically.
Many languages developed after C, were influenced by and borrowed aspects of C, including [[C++]], [[C Sharp (programming language)|C#]], [[C shell]], [[D (programming language)|D]], [[Go (programming language)|Go]], [[Java (programming language)|Java]], [[JavaScript]], [[Julia (programming language)|Julia]], [[Limbo (programming language)|Limbo]], [[LPC (programming language)|LPC]], [[Objective-C]], [[Perl]], [[PHP]], [[Python (programming language)|Python]], [[Ruby (programming language)|Ruby]], [[Rust (programming language)|Rust]], [[Swift (programming language)|Swift]], [[Verilog]] and [[SystemVerilog]].<ref name="vinsp" /><ref name="kafmy">{{Cite book|title=Pillars of computing : a compendium of select, pivotal technology firms |last1=O'Regan |first1=Gerard |isbn=978-3319214641 |oclc=922324121 |date=September 24, 2015|publisher=Springer }}</ref> Some claim that the most pervasive influence has been syntactical {{endash}} that these languages combine the statement and expression syntax of C with type systems, data models and large-scale program structures that differ from those of C, sometimes radically.
 
Several C or near-C interpreters exist, including [[Ch (computer programming)|Ch]] and [[CINT]], which can also be used for scripting.
Line 599 ⟶ 600:
The [[C++]] programming language (originally named "C with [[Class (programming)|Classes]]") was devised by [[Bjarne Stroustrup]] as an approach to providing [[Object-oriented programming|object-oriented]] functionality with a C-like syntax.<ref name="stroustrup 1993">{{cite web |url=http://www.stroustrup.com/hopl2.pdf |title=A History of C++: 1979–1991 |first1=Bjarne |last1=Stroustrup |author-link=Bjarne Stroustrup |year=1993 |access-date=June 9, 2011 |archive-date=February 2, 2019 |archive-url=https://web.archive.org/web/20190202050609/http://www.stroustrup.com/hopl2.pdf |url-status=live }}</ref> C++ adds greater typing strength, scoping, and other tools useful in object-oriented programming, and permits [[generic programming]] via templates. Nearly a superset of C, C++ now{{when|date=August 2022}} supports most of C, with [[Compatibility of C and C++|a few exceptions]].
 
[[Objective-C]] was originally a very "thin" layer on top of C, and remains a strict [[superset]] of C that permits object-oriented programming using a hybrid dynamic/static typing paradigm. Objective-C derives its syntax from both C and [[Smalltalk]]: syntax that involves preprocessing, expressions, function declarations, and function calls is inherited from C, while the syntax for object-oriented features was originally taken from Smalltalk.
 
In addition to [[C++]] and [[Objective-C]], [[Ch (computer programming)|Ch]], [[Cilk]], and [[Unified Parallel C]] are nearly supersets of C.
 
== See also ==
{{Portal|Computer programming|Free and open-source software}}
* [[Compatibility of C and C++]]
* [[Comparison of Pascal and C]]
Line 616:
 
== References ==
{{reflistReflist |30em}}
 
== Sources ==
{{Refbegin |30em |indent=yes}}
* {{cite journal |last1=Ritchie |first1=Dennis M. |author-link=Dennis Ritchie |date=March 1993 |title=The Development of the C Language |journal=ACM SIGPLAN Notices |volume=28 |issue=3 |pages=201–208 |doi=10.1145/155360.155580 |publisher=ACM|doi-access=free }}
*{{cite Q |Q63565563 |last1=Kernighan |first1=Brian W. |author1-link=Brian Kernighan |last2=Ritchie |first2=Dennis M. |author2-link=Dennis Ritchie |publication-date=1978 }}{{sfn whitelist|CITEREFKernighanRitchie1978}}
** By courtesy of the author, also at {{cite web |last1=Ritchie |first1=Dennis M |title=Chistory |url=https://www.bell-labs.com/usr/dmr/www/chist.html |website=www.bell-labs.com |access-date=March 29, 2022}}
*{{cite Q |Q63413168 |last1=Kernighan |first1=Brian W. |author1-link=Brian Kernighan |last2=Ritchie |first2=Dennis M. |author2-link=Dennis Ritchie |publication-date=1988 }}{{sfn whitelist|CITEREFKernighanRitchie1988}}
* {{cite conference |ref=none |last1=Ritchie |first1=Dennis M. |year=1993 |title=The Development of the C Language |pages=201–208 |doi=10.1145/154766.155580 |url=http://www.bell-labs.com/usr/dmr/www/chist.html |book-title=The Second ACM SIGPLAN Conference on History of Programming Languages (HOPL-II) |publisher=[[Association for Computing Machinery|ACM]] |isbn=0-89791-570-4 |access-date=November 4, 2014 |archive-date=April 11, 2019 |archive-url=https://web.archive.org/web/20190411002159/http://www.bell-labs.com/usr/dmr/www/chist.html |url-status=dead }}
* {{cite bookQ |last1=KernighanQ55869040 |first1=Brian W. |author-link=Brian Kernighan |last2last=Ritchie |first2first=Dennis M. |author-link2link=Dennis Ritchie |yearpublication-date=1988March 1993a |titleeditor-last=The C Programming LanguageWexelblat |publishereditor-first=[[PrenticeRichard Hall]]L. |editioneditor-link=2ndRichard Wexelblat }}{{sfn whitelist|isbn=0-13-110362-8CITEREFRitchie1993a}}
*{{cite Q |Q29392176 |last=Ritchie |first=Dennis M. |author-link=Dennis Ritchie |publication-date=1993b |editor1-last=Bergin |editor1-first=Thomas J. |editor2-last=Gibson |editor2-first=Richard G. }}{{sfn whitelist|CITEREFRitchie1993b}}
*{{cite Q |Q134885774 |last=Ritchie |first=Dennis M. |author-link=Dennis Ritchie |publication-date=2003 |orig-date=1993 |via=Bell Labs/Lucent Technologies }}{{sfn whitelist|CITEREFRitchie2003}}
{{Refend}}
 
== Further reading ==
{{Refbegin |30em |indent=yes}}
* {{cite book |last1=Plauger |first1=P.J. |author-link=P. J. Plauger |title=The Standard C Library |edition=1 |year=1992 |publisher=Prentice Hall |isbn=978-0131315099}} <small>[https://github.com/wuzhouhui/c_standard_lib ''(source)'']</small>
* {{cite book |last1=Banahan |first1=M. |last2=Brady |first2=D. |last3=Doran |first3=M. |title=The C Book: Featuring the ANSI C Standard |edition=2 |year=1991 |publisher=Addison-Wesley |isbn=978-0201544336}} <small>[https://github.com/wardvanwanrooij/thecbook ''(free)'']</small>
Line 635 ⟶ 639:
* {{cite book |last1=Deitel |first1=Paul |last2=Deitel |first2=Harvey |title=C: How to Program |edition=8 |year=2015 |publisher=Pearson |isbn=978-0133976892}}
* {{cite book |last1=Gustedt |first1=Jens |title=Modern C |edition=2 |year=2019 |publisher=Manning |isbn=978-1617295812}} <small>''[https://gustedt.gitlabpages.inria.fr/modern-c/ (free)]''</small>
{{Refend}}
 
== External links ==
{{Sister project links |v=C |commons=Category:C (programming language) |b=C Programming |voy=no |s=no |wikt=no}}
* [https://www.open-std.org/jtc1/sc22/wg14/ ISO C Working Group official website]
** [https://www.open-std.org/JTC1/SC22/WG14/www/standards ISO/IEC 9899], publicly available official C documents, including the C99 Rationale
Line 645 ⟶ 649:
* [https://en.cppreference.com/w/c C Library Reference and Examples]
 
{{Subject bar |auto=y |v=C |commons=Category:C (programming language) |b=C Programming |portal1=Computer programming }}
{{C programming language|state=expanded}}
{{Integrated development environments}}
{{Programming languages}}
 
{{Authority control}}
 
Line 663 ⟶ 667:
[[Category:Statically typed programming languages]]
[[Category:Systems programming languages]]
[[Category:Compiled programming languages]]