---
title: C (programming language)
slug: c-programming-language
qid: 
snapshot: enwiki-001378277749
content_hash: 
license: CC BY-SA 4.0
source: https://en.wikipedia.org/w/index.php?oldid=1378277749
tags: [107016903, 115723118, 116690184, 129336739, 20161863, 20232832, 20286173, 20304924, 22914839, 22929646, 22937187, 23026055, 23117742, 23603337, 23837581, 24043274, 24623845, 24705319, 24745107, 24745122, 24769764, 26220375, 26863021, 27367243, 27383506, 28081657, 28493674, 29815558, 29815560, 30142922, 31621131, 3471525, 39178665, 40211111, 40377096, 41309532, 50998678, 52936488, 70184960, 72913447, 89061531, 89061614]
---

# C (programming language)

> [!note] Provenance
> Snapshot `enwiki-001378277749` · content root `…`
> Derived from <https://en.wikipedia.org/w/index.php?oldid=1378277749> · Licensed CC BY-SA 4.0

C is a general-purpose programming language created in 1972 by Dennis Ritchie. By design, C gives programmers relatively direct access to the features of typical CPU architectures, customized for the target instruction set. It has been and continues to be used to implement operating systems (especially kernels ), device drivers, and protocol stacks, though its use in application software is decreasing. C is used on computers ranging from supercomputers to microcontrollers and embedded systems. C was initially developed as a successor to the B programming language at Bell Labs by Ritchie between 1972 and 1973. Its initial purpose was to construct utilities running on Unix, and was later applied to re-implementing the kernel of the Unix operating system. During the 1980s, C gradually gained popularity, leading to it becoming one of the most widely used programming languages, with C compilers available for practically all modern computer architectures and operating systems. 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. 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 a general-purpose programming language created in 1972 by Dennis Ritchie. By design, C gives programmers relatively direct access to the features of typical CPU architectures, customized for the target instruction set. It has been and continues to be used to implement operating systems (especially kernels ), device drivers, and protocol stacks, though its use in application software is decreasing. C is used on computers ranging from supercomputers to microcontrollers and embedded systems. C was initially developed as a successor to the B programming language at Bell Labs by Ritchie between 1972 and 1973. Its initial purpose was to construct utilities running on Unix, and was later applied to re-implementing the kernel of the Unix operating system. During the 1980s, C gradually gained popularity, leading to it becoming one of the most widely used programming languages, with C compilers available for practically all modern computer architectures and operating systems. 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. 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 procedural language, supporting structured programming, lexical variable scope, and recursion, with a static type system. It was designed to be compiled to provide low-level access to memory and language constructs that map efficiently to machine instructions, all with minimal runtime support. Despite its low-level capabilities, the language was designed to encourage cross-platform programming. A standards-compliant C program written with 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 orientation and garbage collection are provided by external libraries GLib Object System and Boehm garbage collector, respectively. Since 2000, C has typically ranked as the most or second-most popular language in the TIOBE index. Parameters are passed by value; pass-by-reference is achieved with pointers. A function's return value may be ignored, and while a function cannot normally be nested inside another function, some translators support this. C supports recursion, and run-time polymorphism may be achieved using function pointers. Control flow is provided through constructs such as if , for , do , while , and switch . The language offers arithmetic; bitwise; and logical operators including + , += , ++ , & , || , and multiple assignments may be performed in a single statement. A variable declared inside a block is accessible only within that block and only below its declaration. Data typing is weakly enforced and static, with implicit conversion between primitive types. User-defined types allow aliasing of type specifiers. Arrays are defined and accessed with square-bracket notation, for example month[11] . User-defined structure types let related data elements be passed and copied as a unit, though two structures cannot be compared without custom code to compare each field. Unions support overlapping members, allowing multiple data types to share the same memory location, and enumeration types support aliasing integer values. C lacks a dedicated string type but provides syntax for null-terminated strings, with associated handling in its standard library. The language supports low-level access to computer memory via pointers, procedure-like constructs in the form of functions returning void , and dynamic memory allocation through standard library functions. It includes the C preprocessor for macro definition, source-file inclusion, and conditional compilation. Modularity is supported by processing files separately, with visibility controlled through the static and extern attributes. Functionality is minimized in the core language, with relatively complex features such as I/O, string manipulation, and mathematical functions being provided through standard libraries. The resulting compiled code has relatively straightforward requirements of the underlying platform, making C desirable for operating and embedded systems. == "Hello, world" example == (1978) The "Hello, World!" program example that appeared in the first edition of 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: main() { printf("hello, world\n"); } A more modern version is: include int main(void) { printf("hello, world\n"); } The first line is a preprocessor directive, indicated by #include , which causes the preprocessor to replace that line of code with the text of the stdio.h header file, which contains declarations for input and output functions including printf . The angle brackets around stdio.h 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 main . The run-time environment calls this function to begin program execution. The type specifier int indicates that the function returns an integer value. The void parameter list indicates that the function consumes no arguments. The run-time environment actually passes two arguments (typed int and char *[] ), 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 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 printf with the address of the first character of a null-terminated string specified as a string literal. The text \n 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 printf returns an int value, it is silently discarded. The semicolon ; terminates the call statement. The closing curly brace indicates the end of the main function. Prior to C99, an explicit return 0; statement was required at the end of main function, but since C99, the main function (as being the initial function call) implicitly returns 0 upon reaching its final closing curly brace. Compound assignment operators of the form =op (such as =- ) were changed to the form op= (that is, -= ) to remove the semantic ambiguity created by constructs such as i=-10 , which had been interpreted as i&nbsp;=-&nbsp;10 (decrement i by 10) instead of the possibly intended i&nbsp;=&nbsp;-10 (let i be −10). Even after the publication of the 1989 ANSI standard, for many years K&R C was still considered the "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. Although later versions of C require functions to have an explicit type declaration, K&R C only requires functions that return a type other than int to be declared before use. Functions used without prior declaration were presumed to return int . For example: long long_function(); calling_function() { long longvar; register intvar; longvar = long_function(); if (longvar > 1) intvar = 0; else intvar = int_function(); return intvar; } The declaration of (on line 1) is required since it returns ; not . Function can be called (line 11) even though it is not declared since it returns . Also, variable does not need to be declared as type since that is the default type for keyword. Since function declarations did not include information about arguments, type checks were not performed, although some compilers would issue a warning if different calls to a function used different numbers or types of arguments. Tools such as Unix's lint utility were developed that (among other things) checked 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 PCC ) and other vendors. These included: void functions; functions returning no value Functions returning struct or union types Assignment for struct variables Enumerated types The popularity of the language, lack of agreement on standard library interfaces, and lack of compliance to the K&R specification, led to standardization efforts. Graphic characters: ! " # % & ' ( ) * + , - . / : ; ? [ \ ] ^ _ { | } ~ Whitespace characters: space, horizontal tab, vertical tab, form feed, newline 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 literals, but they are not entirely portable. Since C99 multi-national Unicode characters can be embedded portably within C source text by using \uXXXX or \UXXXXXXXX encoding (where X denotes a hexadecimal character). The basic C execution character set contains the same characters, along with representations for the null character, alert, backspace, and carriage return. Run-time support for extended character sets has increased with each revision of the C standard. assignment: = augmented assignment: bitwise logic: ~ , & , | , ^ bitwise shifts: &lt;&lt; , &gt;&gt; Boolean logic: ! , && , || conditional evaluation: ? : equality testing: == , != calling functions: ( ) increment and decrement: ++ , -- member selection: . , -> object size: sizeof type: typeof , typeof_unqual since C23 order relations: &lt; , &lt;= , &gt; , &gt;= reference and dereference: & , * , [ ] sequencing: , subexpression grouping: ( ) type conversion: (typename) C uses the operator = (used in mathematics to express equality) to indicate assignment, following the precedent of Fortran and PL/I, but unlike ALGOL and its derivatives. C uses the operator == to test for equality. The similarity between the operators for assignment and equality may result in the accidental use of one in place of the other, and in many cases the mistake does not produce an error message (although some compilers produce warnings). For example, the conditional expression if (a == b + 1) might mistakenly be written as if (a = b + 1) , which will be evaluated as true unless the value of a is 0 after the assignment. The C operator precedence is not always intuitive. For example, the operator == binds more tightly than (is executed prior to) the operators & (bitwise AND) and | (bitwise OR) in expressions such as x & 1 == 0 , which must be written as (x & 1) == 0 if that is the coder's intent. int func(int n, int m) { float (*p)[n][m] = malloc(sizeof *p); if (p == NULL) { return -1; } for (int i = 0; i And here is a similar implementation using C99's Auto VLA feature: int func(int n, int m) { // Caution: checks should be made to ensure n * m * sizeof(float) does NOT exceed limitations for auto VLAs and is within available size of stack. float p[n][m]; // auto VLA is held on the stack, and sized when the function is invoked for (int i = 0; i The total size of an array x can be determined by applying sizeof to an expression of array type. The size of an element can be determined by applying the operator sizeof to any dereferenced element of an array A , as in n = sizeof A[0] . Thus, the number of elements in a declared array A can be determined as sizeof A / sizeof A[0] . 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. ===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. ===World Wide Web=== Historically, C was sometimes used for web development using the Common Gateway Interface (CGI) as a "gateway" for information between the web application, the server, and the browser. C may have been chosen over interpreted languages because of its speed, stability, and near-universal availability. It is no longer common practice for web development to be done in C, and many other web development languages are popular. Applications where C-based web development continues include the HTTP configuration pages on routers, IoT devices and similar, although even here some projects have parts in higher-level languages e.g. the use of Lua within OpenWRT. Two popular web servers, Apache HTTP Server and nginx, are written in C. C's close-to-the-metal approach allows for the construction of these high-performance software systems. ===C as an intermediate language=== C is sometimes used as an intermediate language by implementations of other languages. This approach may be used for portability or convenience; by using C as an intermediate language, additional machine-specific code generators are not necessary. C has some features, such as line-number preprocessor directives and optional superfluous commas at the end of initializer lists, that support compilation of generated code. However, some of C's shortcomings have prompted the development of other C-based languages specifically designed for use as intermediate languages, such as C--. Also, contemporary major compilers GCC and LLVM both feature an intermediate representation that is not C, and those compilers support front ends for many languages including C. ===Computationally intensive libraries=== C enables programmers to create efficient implementations of algorithms and data structures, because the layer of abstraction from hardware is thin, and its overhead is low, an important criterion for computationally intensive programs. For example, the GNU Multiple Precision Arithmetic Library, the GNU Scientific Library, Mathematica, and MATLAB are completely or partially written in C. Many languages support calling library functions in C; for example, the Python-based framework NumPy uses C for the high-performance and hardware-interacting aspects. ===Other languages are written in C=== A consequence of C's wide availability and efficiency is that compilers, libraries and interpreters of other programming languages are often implemented in C. For example, the reference implementations of Python, Perl, Ruby, and PHP are written in C. ==Limitations== Ritchie himself joked about the limitations of the language that he created: While C is popular, influential and hugely successful, it has drawbacks, including: The standard dynamic memory handling with malloc and free is prone to mistakes. Improper use can lead to memory leaks and dangling pointers. 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 weakly typed, despite being statically typed. Since the code generated by the compiler contains few run-time checks, there is a burden on the programmer to consider all possible outcomes, to protect against buffer overruns, array bounds checking, stack overflows, memory exhaustion, and consider race conditions, thread isolation, etc. The use of pointers and the run-time manipulation of these enables 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. Some of the standard library functions, e.g. scanf or , can lead to buffer overruns. There is limited standardization in support for low-level variants in generated code, such as different function calling conventions and ABIs; different structure packing conventions; and different byte ordering within larger integers (including endianness). In many language implementations, some of these options may be handled with the preprocessor directive #pragma , and some with additional keywords e.g. use __cdecl calling convention. The directive and options are not consistently supported. String handling using the standard library is code-intensive, with explicit memory management required. The language does not directly support object orientation, introspection, run-time expression evaluation (like eval in JavaScript), garbage collection, etc. There are few guards against misuse of language features, which may enable unmaintainable code. In particular, the C preprocessor can hide troubling effects such as double evaluation and worse. This capability for obfuscated 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 codes for error checking. The setjmp and longjmp standard library functions have been used to implement a try-catch mechanism via macros. Also, goto statements are commonly used for error handling.
