The C programming language (often, just "C") is a general-purpose, procedural, imperative computer programming language developed in the early 1970s by Dennis Ritchie for use on the Unix operating system. It has since spread to many other operating systems, and is now one of the most widely used programming languages. C has also had a great influence on most other popular languages, especially C++ which was originally designed as an enhancement to C. It is distinguished for the efficiency of the code it produces, and is the most commonly used programming language for writing system software, though it is also widely used for writing applications. Though not originally designed as a language for teaching, and despite its somewhat unforgiving character, C is commonly used in computer science education, in part because the language is so pervasive. Note that C# is a very different programming language.
In part due to the language's low level and modest feature set, C compilers can be developed comparatively easily. The language has therefore become available on a very wide range of platforms (probably more than for any other programming language in existence). Furthermore, despite its low-level nature, the language was designed to enable (and to encourage) machine-independent programming. A standards-compliant and portably written C program can therefore be compiled for a very wide variety of computer platforms and operating systems with minimal change to its source code.
C was originally developed (along with the Unix operating system with which it has long been associated) by programmers and for programmers, with few users other than its own designers in mind. Nevertheless, it has achieved very widespread popularity, finding application in contexts far removed from its roots as a language for systems-programming.
As an Algol-based language, C has the following characteristics:
C also has the following specific properties:
As a systems implementation language, C lacks features found in other languages:
A..B notation used in both newer and older languages (does not fit scalar-only semantics well).
errno variable
Although the list of built-in features C lacks is long, this has contributed significantly to its acceptance, as new C compilers can be developed quickly for new platforms. The relatively low-level nature of the language affords the programmer close control over what the program is doing, while allowing solutions that can be specially tailored and aggressively optimized for a particular platform. This allows the code to run efficiently on very limited hardware, such as mass-produced consumer embedded systems, which today are as capable as the first machines used to implement C. Often, only hand-tuned assembly language code runs faster, although advances in compiler technology have gradually narrowed this gap.
In some cases, a missing feature can be approximated within C. For example, the original implementation of C++ consisted of a preprocessor that translated the C++ syntax into C source code. Most object oriented functions include a special "this" pointer, which refers to the current object. By passing this pointer as a function argument in C, the same functionality can be performed in C. For example, in C++ one might write: stack->push(val); while in C, one would write: push(stack,val); where the stack argument of C is a pointer to a struct which is equivalent to the this pointer of C++, which is a pointer to an object.
There are many legends as to the origin of C and the closely related Unix operating system, including:
By 1973, the C language had become powerful enough that most of the Unix kernel, originally written in PDP-11/20 assembly language, was rewritten in C. This was one of the first operating system kernels implemented in a language other than assembly. (Earlier instances include the Multics system (written in PL/I), and MCP (Master Control Program) for Burroughs B5000 written in ALGOL in 1961.)
K&R introduced the following features to the language:
struct data types
long int data type
unsigned int data type
=+ operator was changed to += to remove the semantic ambiguity created by the construct i=+10, which could be interpreted as either i =+ 10 or i = +10
K&R C is often considered the most basic part of the language that a C compiler must support. For many years, even after the introduction of ANSI C, it was considered the "lowest common denominator" to which C programmers restricted themselves when maximum portability was desired, since not all compilers were updated to fully support ANSI C, and because with care, K&R C code can be written to be legal ANSI C as well.
In these early versions of C, only functions that returned a non-integer value needed to be declared if used before the function definition. A function used without any previous declaration was assumed to return an integer.
Example call requiring previous declaration:
long int SomeFunction(); int CallingFunction() { long int ret; ret = SomeFunction(); }
Example call not requiring previous declaration:
int CallingFunction() { int ret; ret = SomeOtherFunction(); } int SomeOtherFunction() { return 0; }
Since the K&R prototype did not include any information about function arguments, function parameter type checks were not performed, although some compilers would issue a warning message if a function was called with the wrong number of arguments.
In the years following the publication of K&R C, several "unofficial" features were added to the language, supported by compilers from AT&T and some other vendors. These included:
void functions and void * data type
struct or union types (rather than pointers)
struct data types
const qualifier to make an object read-only
In 1983, the American National Standards Institute (ANSI) formed a committee, X3J11, to establish a standard specification of C. After a long and arduous process, the standard was completed in 1989 and ratified as ANSI X3.159-1989 "Programming Language C." This version of the language is often referred to as ANSI C, or sometimes C89 (to distinguish it from C99).
In 1990, the ANSI C standard (with a few minor modifications) was adopted by the International Organization for Standardization (ISO) as ISO/IEC 9899:1990. This version is sometimes called C90. Therefore, the terms "C89" and "C90" refer to essentially the same language.
One of the aims of the ANSI C standardization process was to produce a superset of K&R C, incorporating many of the unofficial features subsequently introduced. However, the standards committee also included several new features, such as function prototypes (borrowed from C++), and a more capable preprocessor. The syntax for parameter declarations was also changed to reflect the C++ style:
int main(argc, argv)
int argc;
char **argv;
{
...
}
became
int main(int argc, char *argv*) { ... }
ANSI C is now supported by almost all the widely used C compilers. Most of the C code being written nowadays is based on ANSI C. Any program written only in standard C and without any hardware dependent assumptions is virtually guaranteed to run correctly on any platform with a conforming C implementation. Without such precautions, most programs may compile only on a certain platform or with a particular compiler, due, for example, to the use of non-standard libraries, such as GUI libraries, or to the reliance on compiler- or platform-specific attributes such as the exact size of certain data types and byte endianness.
To mitigate the differences between K&R C and the ANSI C standard, the __STDC__ macro can be used to split code into ANSI and K&R sections.
extern int getopt(int,char * const *,const char *);
- if __STDC__
extern int getopt();
- else
- endif
Some suggest using "#if __STDC__" as above rather than "#ifdef __STDC__" because some compilers set __STDC__ to zero to indicate non-ANSI compliance.
After the ANSI standardization process, the C language specification remained relatively static for some time, whereas C++ continued to evolve. (Normative Amendment 1 created a new version of the C language in 1995, but this version is rarely acknowledged.) However, the standard underwent revision in the late 1990s, leading to the publication of ISO 9899:1999 in 1999. This standard is commonly referred to as "C99." It was adopted as an ANSI standard in March 2000.
C99 introduced several new features, many of which had already been implemented as extensions in several compilers:
long long int (to reduce the pain of the looming 32-bit to 64-bit transition), an explicit boolean data type, fixed-width integer types, and a complex type to represent complex numbers
//, as in BCPL or C++
snprintf()
stdint.h
C99 is stricter in some ways than previous versions; for example it is (generally) illegal for pointers of different types to reference the same memory location (aliasing). This allows improved optimisation but can break older programs.
GCC and several other C compilers now support most of the new features of C99. However, there has been less support from vendors such as Microsoft and Borland that have been mainly focused on C++, since C++ provides similar functionality in often incompatible ways (e.g., the complex template class). Microsoft's Brandon Bray said "In general, we have seen little demand for many C99 features. Some features have more demand than others, and we will consider them in future releases provided they are compatible with C++." *
Even GCC with its extensive C99 support still does not approach a completely compliant implementation; several key features are missing or don't work correctly.*
C is used as an intermediate language by some higher-level languages. This is implemented in one of two ways, as languages which:
C source code is then input to a C compiler, which then outputs finished object or machine code. This is done to gain portability and optimization. C compilers exist for nearly all processors and operating systems, and most C compilers output well optimized object or machine code. Thus, any language that outputs C source code suddenly becomes very portable, and able to yield optimized object or machine code.
Unfortunately, C is designed as a programming language, not as a compiler target language, and is thus less than ideal for use as an intermediate language. This has led to development of C-based intermediate languages such as C--.
Unlike languages such as FORTRAN 77, C source code is free-form, allowing programmers to use arbitrary whitespace in formatting their code, rather than having to lay out their code according to certain column-based restrictions. Comments can be included either between the delimiters /* and */, or (in C99) following // until the end of the line.
Each source file contains declarations and function definitions. Function definitions, in turn, contain declarations and statements. Declarations either define new types using keywords such as struct, union, and enum, or assign types to and perhaps reserve storage for new variables, usually by writing the type followed by the variable name. Keywords such as char and int, as well as the pointer-to symbol *, specify built-in types. Sections of code are enclosed in braces ({ and }) to indicate the extent to which declarations and control structures apply.
As an imperative language, C depends on statements to do most of the work. Most statements are expression statements which simply cause an expression to be evaluated — and, in the process, cause variables to receive new values or values to be printed. Control-flow statements are also available for conditional or iterative execution, constructed with reserved keywords such as if, else, switch, do, while, and for. Arbitrary jumps are possible with goto. A variety of built-in operators perform primitive arithmetic, Boolean logical, comparative, bitwise logical, and array indexing operations and assignment. Expressions can also invoke functions, including a large number of standard library functions, for performing many common tasks.
main() { printf("hello, world\n"); }
The above program will compile correctly on most modern compilers that are not in compliance mode. However, it produces several warning messages when compiled with a compiler that conforms to the ANSI C standard. Additionally, the code will not compile if the compiler strictly conforms to the C99 standard, as a return value of type int will no longer be assumed if the source code has not specified the return type. Even if it compiles, the resulting program will return an undefined exit status to the environment. These problems can be eliminated with a few minor modifications to the original program:
#include int main(void) { printf("hello, world\n");
return 0; }
What follows is a line-by-line analysis of the above program:
#includeThis first line of the program is a preprocessing directive,
#include. This causes the preprocessor — the first tool to examine source code when it is compiled — to substitute for that line the entire text of the file or other entity to which it refers. In this case, the header stdio.h, which contains the definitions of standard input and output functions, will replace that line. The angle brackets surrounding stdio.h indicate that stdio.h can be found using an implementation-defined search strategy. Double quotes may also be used for headers, thus allowing the implementation to supply (up to) two strategies. Typically, angle brackets are used for headers supplied by the implementation, and double quotes for local or installation-specific headers.
int main(void)This next line indicates that a function named
main is being defined. The main function serves a special purpose in C programs. When they are executed, main() is the first function called. The portion of the code that reads int indicates that the return value, the value to which the main function will evaluate, is an integer. The keyword (void) in between the parentheses indicates that the main function takes no arguments. See also void.
{
This opening curly brace indicates the beginning of the definition of the main function.
printf("hello, world\n");
This line calls (looks up and then executes the code for) a function named printf, which is declared in the included header stdio.h. In this call, the printf function is passed (provided with) a single argument, the address of the first character in the string literal "hello, world\n". The \n is an escape sequence that is translated to the newline character, which on output signifies the beginning of the next line. The return value of the printf function is of type int, but no use was made of it so it will be quietly discarded.
return 0;This line terminates the execution of the
main function and causes it to return the integral value 0, which by convention is the exit code used to indicate successful execution.
}This closing curly brace indicates the end of the code for the
main function.
If the above code were compiled and executed, it would do the following:
enum). There are also derived types including arrays, pointers, records (struct), and untagged unions (union).
C is often used in low-level systems programming, where "escapes" from the type system may be necessary. The compiler attempts to ensure type correctness of most expressions, but the programmer can override the checks in various ways, either by using a typecast to explicitly convert a value from one type to another, or by using pointers or unions to reinterpret the underlying bits of a value in some other way. (The use of typecasts obviously sacrifices some of the safety normally provided by the type system.)
A null pointer is a pointer value that points to no valid location (its internal value is usually zero). (Dereferencing a null pointer is therefore meaningless, typically resulting in a runtime error.) Null pointers are useful for indicating special cases such as the next pointer in the final node of a linked list, or as an error code from functions that return pointers. Pointers to type void also exist, and point to objects of unknown type. A void pointer is therefore used as a "generic pointer" (see also generic programming). Since the size and type of the pointed-to object is not known, void pointers cannot be dereferenced, nor is pointer arithmetic on them possible, although they can easily be (and in fact implicitly are) converted to and from any other object pointer type.
Traditionally, array types in C were always one-dimensional and of a fixed, static size specified at compile time. (The latest "C99" standard does allow some forms of variable-length arrays.) However, it is also perfectly straightforward to allocate a block of memory (of arbitrary size) at run-time using the standard library and treat it as an array. C's unification of arrays and pointers (see below) means that true arrays and these dynamically-allocated, simulated arrays are virtually interchangeable. However, since arrays are always accessed (in effect) via pointers, array accesses are typically not checked against the underlying array size, although the compiler may provide some level of bounds checking as an option. Array bounds violations are therefore possible and rather common (see also the "Criticism" section below), and can lead to the usual sorts of repercussions: illegal memory accesses, corruption of data, run-time exceptions, etc.
C does not have a special provision for declaring multidimensional arrays, but rather relies on recursion within the type system to declare arrays of arrays, which effectively accomplishes the same thing. The index values of the resulting "multidimensional array" can be thought of as increasing in row-major order. There are provisions for accessing the array as a whole, or only particular elements of the array. However, because of the recursive nature of the type system, sub-array access is limited to row-by-row access.
xcan also be used when x is a pointer; the interpretation (using pointer arithmetic) is to access the (i+1)th of several adjacent data objects pointed to by x, counting the object that x points to (which is x[0) as the first element of the array.
Formally, x* is equivalent to *(x + i). Since the type of the pointer involved is known to the compiler at compile time, the address that x + i points to is not the address pointed to by x incremented by i, but rather incremented by i multiplied by the size of the objects that x points to. The size of these objects can be determined with the operator sizeof applied to the object pointed to by the pointer x, as in n = sizeof (*x).
Furthermore, when the name of an array is used in an expression without a subscript (*), the name of the array represents a pointer to the array's first element for the purposes of subsequent expressions; this implies that arrays are never copied as a whole when passed as arguments to functions, but rather only the address of its first element is passed. Therefore, although C's function calls use pass-by-value semantics, arrays are effectively passed by reference.
A powerful demonstration of the remarkable interchangeability of pointers and arrays is shown below. These four lines are equivalent and, from the compiler's point of view, completely correct. Note how the last line shows the strange code i* = 1;, which has the index variable i apparently interchanged with the array variable x. This last line might be found in obfuscated C code.
x* = 1; i* = 1; /* strange, but correct */
- (x + i) = 1;
- (i + x) = 1;
malloc() from a region of memory called the heap; these blocks can be subsequently freed for reuse by calling the library function free()
These three approaches are appropriate in different situations and have various tradeoffs. For example, static memory allocation has no allocation overhead, automatic allocation has a small amount of overhead during initialization, and dynamic memory allocation can potentially have a great deal of overhead for both allocation and deallocation. On the other hand, stack space is typically much more limited than either static memory or heap space, and only dynamic memory allocation allows allocation of objects whose size is known only at run-time. Most C programs make extensive use of all three.
Where possible, automatic or static allocation is usually preferred because the storage is managed by the compiler, freeing the programmer of the potentially error-prone hassle of manually allocating and releasing storage. Unfortunately, many data structures can grow in size at runtime; since automatic and static allocations must have a fixed size at compile-time, there are many situations in which dynamic allocation must be used. Variable-sized arrays are a common example of this (see "malloc" for an example of dynamically allocated arrays).
The C programming language uses libraries as its primary method of extension. In C, a library is a collection of functions contained within a single file. Each library has a header file, which contains the prototypes of the functions contained within the library that may be used by a program. In order for a program to use a library, the header file from that library must be declared at the top of a source file, and the library must be linked to the program, which in many cases requires compiler flags (e.g., -lmath).
The most common C library is the C standard library, which is specified by the ISO and ANSI C standard and comes standard with every modern C compiler. The ANSI C standard library provides functionality for stream input and output, memory allocation, mathematics, character strings, and time values manipulation.
Another common set of C libraries are those used for developing Unix and Unix-like systems, which provide an interface to the kernel. These functions are detailed in various standards such as POSIX and the Single UNIX Specification.
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 generates fast object code; programmers then create interfaces to the library so that the routines can be used from higher-level languages like Java, Perl, and Python.
The designers wanted to avoid compile- and run-time checks that were too expensive when C was first implemented. With time, external tools were developed to perform some of these checks, such as those discussed in Compiler-external static-checking tools below. Nothing prevents an implementation from providing such checks, but nothing requires it to, either. The safe C dialect Cyclone addresses some of these concerns.
Even Kernigan and Ritchie made reference to the basic design philosophy of C in their response to criticism of C not being a strongly-typed languageBrian W. Kernighan and Dennis M. Ritchie: The C Programming Language, 2nd ed., Prentice Hall, 1988, p. 3.: "Nevertheless, C retains the basic philosophy that programmers know what they are doing; it only requires that they state their intentions explicitly."
Another common problem is that heap memory has to be manually synchronized with its actual usage in any program for it to be correctly reused as much as possible. For example, if an automatic pointer variable goes out of scope or has its value overwritten while still referencing a particular allocation that is not freed via a call to free(), then that memory cannot be recovered for later reuse and is essentially lost to the program, a phenomenon known as memory leak. Conversely, it is possible to release memory too soon, and in some cases continue to be able to use it, but since the allocation system can re-allocate the memory at any time for unrelated reasons, this results in unpredictable behavior, typically manifested in portions of the program far removed from the erroneously written segment. Such issues are ameliorated in languages with automatic garbage collection or RAII.
Multidimensional arrays are commonly used in numerical algorithms (mainly from applied linear algebra) to store matrices. The structure of the C array is particularly well suited to this particular task, provided one remembers to count indices starting from 0 instead of 1. This issue is discussed in the book Numerical Recipes in C, chapter 1.2, page 20ff (read online). In that book there is also a solution based on negative addressing which introduces other dangers.
However, type-checking of variadic functions from the standard library is a quality-of-implementation issue; many modern compilers do type-check printf calls, producing warnings if the argument list is inconsistent with the format string. Even so, not all printf calls can be checked statically since the format string can be built at runtime, and other variadic functions typically remain unchecked.
Bjarne Stroustrup said of C++ (which is superficially similar to C): "Within C++, there is a much smaller and cleaner language struggling to get out. the C++ semantics is much cleaner than its syntax." [http://www.research.att.com/~bs/bs_faq.html#really-say-that Some specific problems worth noting are:
binding more tightly than & and | in expressions like x & 1
0.
= operator, used in mathematics for equality, to indicate assignment. Ritchie made this syntax design decision consciously, based primarily on the argument that assignment occurs more often than comparison. However, as explained by computer scientist Damian Conway in his "Seven Deadly Sins of Introductory Programming Language Design": "Many students, when confronted with this operator, become confused as to the nature of assignment and its relationship to equality. it reinforces the notion of procedural transfer of value, rather than transitive equality of value.".[http://citeseer.ist.psu.edu/mciver96seven.html" target="_blank" >*
= and ==) makes it easy to substitute one for the other, and C's weak type system permits each to be used in the context of the other without a compiler error (although some produce warnings).*
Specifying a type in C++ is made difficult by the fact that some of the components of a declaration (such as the pointer specifier) are prefix operators while others (such as the array specifier) are postfix. These declaration operators are also of varying precedence, necessitating careful bracketing to achieve the desired declaration. Furthermore, if the type ID is to apply to an identifier, this identifier ends up at somewhere between these operators, and is therefore obscured in even moderately complicated examples (see Appendix A for instance). The result is that the clarity of such declarations is greatly diminished. Ben Werther & Damian Conway. A Modest Proposal: C++ Resyntaxed. Section 3.1.1. 1996.
t be larger than s, a complication that is handled by the safer library function strncpy(). is the following function to copy the contents of string t to string s:
void strcpy(char *s, char *t) { while (*s++ = *t++); }
In this example, t is a pointer to a null-terminated array of characters, s is a pointer to an array of characters. Every loop of the single while statement does the following:
t (initially set to point to the first character of the string to be copied) to the corresponding character position in s (initially set to point to the first character of the character array to be copied to)
s and t to point to the next character. Note that the values of s and t can safely be changed, because they are local copies of the pointers to the corresponding arrays
((*s++ = *t++) != '\0')" (where '\0' is the null character); however, in C, both Boolean values and characters are represented as small integers and are therefore interchangeable, and consequently the test is true as long as the character has any non-zero value (i.e., is any character other than a string-terminating null)
while loop to repeat. (In particular, because the character copy occurs before the condition is evaluated, the final terminating null is guaranteed to be copied as well)
The above code is functionally equivalent to:
void strcpy(char *s, char *t) { char aux; do { *s = *t; aux = *s; s++; t++; } while (aux != '\0'); }
In a modern optimising compiler, these two pieces of code produce identical assembly code, so the smaller code does not produce smaller output. In more verbose languages such as Pascal, the above single statement would require several statements to implement. For C programmers, the economy of style is idiomatic and leads to shorter expressions; for critics, being able to do too much with a single line of C code can lead to problems in comprehension.
Other voices do not criticize the economy of expression, but instead the lack of boundary checks, blaming it for causing frequent buffer overruns; it is very expensive (in terms of performance) to implement such checks in languages that has only element by element semantics; this problem is therefore hard to solve satisfactorily in languages such as C.
#include) that relies on literal text inclusion and redundantly keeping prototypes and function definitions in sync, and drastically increases build times.
Automated source code checking and auditing are beneficial in any language, and for C many such tools exist, such as Lint. A common practice is to use Lint to detect questionable code when a program is first written. Once a program passes Lint, it is then compiled using the C compiler.
There are also compilers, libraries and operating system level mechanisms for performing array bounds checking, buffer overflow detection, and automatic garbage collection, that are not a standard part of C.
Many compilers, most notably Visual C++, deal with the long compilation times inflicted by header file inclusion using precompiled headers, a system where declarations are stored in an intermediate format that is quick to parse. Building the precompiled header files in the first place is expensive, but this is generally done only for system header files, which are larger and more numerous than most application header files and also change much less often.
Cproto is a program that will read a C source file and output prototypes of all the functions within the source file. This program can be used in conjunction with the "make" command to create new files containing prototypes each time the source file has been changed. These prototype files can be included by the original source file (e.g., as "filename.p"), which reduces the problems of keeping function definitions and source files in agreement.
It should be recognized that these tools are not a panacea. Because of C's flexibility, some types of errors involving misuse of variadic functions, out-of-bounds array indexing, and incorrect memory management cannot be detected on some architectures without incurring a significant performance penalty. However, some common cases can be recognized and accounted for.
C programming language | Programming languages | Curly bracket programming languages
C (programmeertaal) | سي | Lenguache de programazión C | Llinguaxe de programación C | C | C (мова праграмавання) | C programski jezik | C (език за програмиране) | Llenguatge C | C (programovací jazyk) | C (programmeringssprog) | C (Programmiersprache) | C (programmeerimiskeel) | C (γλώσσα προγραμματισμού) | Lenguaje de programación C | Biblioteca C | C (programlingvo) | C programazio lengoaia | C (langage) | C (Teanga ríomhchlárúcháin) | Linguaxe de programación C | C 프로그래밍 언어 | C (programski jezik) | Bahasa pemrograman C | C (linguage de programmation) | Forritunarmálið C | C (linguaggio) | C (שפת תכנות) | C (zimanê bernamekirinê) | C (codex programmandi) | C (programmēšanas valoda) | C (kalba) | C programozási nyelv | Bahasa pengaturcaraan C | C (programmeertaal) | C言語 | C (programmeringsspråk) | Programmeringsspråket C | C (język programowania) | Linguagem de programação C | Limbajul C | Си (язык программирования) | Gjuha programuese C | C programming language | C (programovací jazyk) | Programski jezik C | Програмски језик C | C (jezik) | C (ohjelmointikieli) | C (programspråk) | சி நிரலாக்கல் மொழி | ภาษาซี | C (ngôn ngữ lập trình) | C programlama dili | C (мова програмування) | C语言
This article is licensed under the GNU Free Documentation License.
It uses material from the
"C programming language".
Home Page • arts • business • computers • games • health • hospitals • home • kids & teens • news • physicians • recreation• reference • regional • science • shopping • society • sports • world