[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 }}
{{Infobox programming language
| name = C
| logo = The C Programming Language logo.svg
| 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}}
| influenced by = [[B (programming language)|B]] ([[BCPL]], [[CPL (programming language)|CPL]]), [[ALGOL 68]],
| 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}}
| wikibooks = C Programming
}}
'''C'''
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.
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>
==
[[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:
{{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|+|+{{=}}|++|&|{{!!}}|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 ==
[[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}}
<syntaxhighlight lang="c">
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.}}
<!-- 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 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.
==== 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'']],
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 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.
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]].
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]]''.
''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.
For example:
<syntaxhighlight lang="c" line>
long long_function();
calling_function()
{
long
register intvar;
longvar = long_function();
if (longvar > 1)
intvar = 0;
else
return
}
</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.
Since
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
* <code>[[void type|void]]</code> functions
*
* [[Assignment (computer science)|
* [[Enumerated type]]s
The
=== 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
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
=== 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.
==
{{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 ===
C89 has 32 reserved words:
{{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 ===
{{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 ==
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
* 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
===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==
{{blockquote |text=the power of assembly language and the convenience of ... assembly language |author=Dennis Ritchie}}
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 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.
* 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 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 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
* [[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),
* There are few guards against
* 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
There are [[#Language tools|tools]] that can mitigate
== Related languages ==
[[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}}
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
In addition to [[C++]] and [[Objective-C]], [[Ch (computer programming)|Ch]], [[Cilk]], and [[Unified Parallel C]] are nearly supersets of C.
== See also ==
* [[Compatibility of C and C++]]
* [[Comparison of Pascal and C]]
Line 616:
== References ==
{{
== Sources ==
{{Refbegin |30em |indent=yes}}
*{{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}}
*{{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 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 ==
* [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]]
|