Jump to content

C (programming language): Difference between revisions

From Wikipedia, the free encyclopedia
[pending revision][pending revision]
Content deleted Content added
removed false claim
Resources: Point at the current CLC FAQ and add reference to the CLC Wiki
(876 intermediate revisions by more than 100 users not shown)
Line 1: Line 1:
[[Image:K&R_C.jpg|thumb|right|''[[The C Programming Language (book)|The C Programming Language]]'', [[Brian Kernighan]] and [[Dennis Ritchie]], the original edition that served for many years as an informal specification of the language]]
[[ca:Llenguatge C]]
[[de:C (Programmiersprache)]]
[[eo:C Komputillingvo]]
[[fr:Langage C]]
[[he:C]]
[[nl:Programmeertaal C]]
[[hu:C Programozási nyelv]]
[[ja:C言語]]
[[pl:C (jêzyk programowania)]]
[[pt:C Programming Language]]
[[sv:Programspråket C]]
[[zh:C编程语言]]


'''C''' is a [[programming language]] developed by [[Ken Thompson]] and [[Dennis Ritchie]], in the early [[1970s]], for use on the [[UNIX]] [[operating system]]. It is now used on practically every operating system, and is the most popular language for writing [[system software]], though it is also used for writing [[application]]s. It is also commonly used in [[computer science]] [[education]]. The popular [[C Plus Plus|C++]] programming language is based on C.
The '''C programming language''' is a standardized [[imperative programming|imperative]] [[computer programming|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 one of the most widely used programming languages. C is prized for its efficiency, and is the most popular programming language for writing [[system software]], though it is also used for writing [[Application software|application]]s. It is also commonly used in [[computer science]] [[education]], despite not being designed for novices.


== Features ==
==History==
===Early developments===
The initial development of C occurred at [[AT&T]] [[Bell Labs]] between 1969 and 1973; according to Ritchie, the most creative period occurred in 1972. It was named "C" because many of its features were derived from an earlier language called "[[B programming language|B]]".
Accounts differ regarding the origins of the name "B": [[Ken Thompson]] credits the [[BCPL]] programming language, but he had also created a language called [[Bon (programming language)|Bon]] in honor of his wife Bonnie.


There are many legends as to the origin of C and its related operating system, [[Unix]], including:
C is a relatively minimalist programming language. It is significantly lower-level than most other programming languages. Even though it is sometimes referred to as a "[[high level language]]", it is only really higher-level than the various [[assembly language]]s.
* The development of C was the result of the programmers' desire to play [http://cm.bell-labs.com/cm/cs/who/dmr/spacetravel.html Space Travel]. They had been playing it on their company's [[mainframe]], but being underpowered and having to support about 100 users, Thompson and Ritchie found they didn't have sufficient control over the spaceship to avoid collisions with the wandering [[asteroid|space rocks]]. Thus, they decided to port the game to an idle [[PDP-7]] in the office. But it didn't have an [[operating system]] (OS), so they set about writing one. Eventually they decided to port the operating system to the office's [[PDP-11]], but this was [[wiktionary:onerous|onerous]] since all the code was in [[assembly language]]. They decided to use a higher-level portable language so the OS could be ported easily from one computer to another. They looked at using B, but it lacked functionality to take advantage of some of the PDP-11's advanced features. So they set about creating the new language, C.
*The justification for obtaining the original computer that was used to develop Unix was to create a system to automate the filing of patents. The original version of Unix was developed in assembly language. Later, the C language was developed in order to rewrite the operating system.


By 1973, the C language had become powerful enough that most of the [[Unix]] [[kernel (computers)|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 programming language|PL/I]]), and MCP ([[Master Control Program]]) for Burroughs [[B5000]] written in [[ALGOL]] in 1961.)
C has two important advantages over assembly. Firstly, [[source code|code]] is generally easier to read and much less burdensome to write, especially for lengthy programs. Secondly, assembly code is usually applicable only to a specific [[computer architecture]], whereas a C program can be [[porting|ported]] to any architecture on which a C [[compiler]] and certain required [[library (computer science)|libraries]] exist. (C code is almost always compiled, rather than [[interpreted language|interpreted]].) On the other hand, the efficiency of C code is somewhat dependent on the ability of the compiler to [[Optimization (computer science)|optimize]] the resulting [[machine language]], which is largely out of the programmer's control. In contrast, the efficiency of assembly code is precisely determined, since assembly is just human-readable notation for a machine language. For this reason, programs such as operating system [[kernel (software engineering)|kernel]]s, though mostly written in C, may contain "hand-tuned" fragments of assembly language where performance is especially crucial.


===K&R C===
Similar advantages and disadvantages distinguish C from higher-level languages: the efficiency of C code can be more closely controlled, at the cost of being generally more troublesome to read and write. Note, however, that C is ''at least'' as portable as higher-level languages, because nowadays most computer architectures are equipped with a C compiler and libraries; in fact, the compilers, libraries, and interpreters of higher-level languages are often implemented in C!
In 1978, Ritchie and [[Brian Kernighan]] published the first edition of ''[[The C Programming Language (book) | The C Programming Language]]''. This book, known to C programmers as "K&R", served for many years as an informal [[specification]] of the language. The version of C that it describes is commonly referred to as "K&R C." (The second edition of the book covers the later [[ANSI C]] standard, described below.)


K&R introduced the following features to the language:
One of the most notable features of C is that it is up to the programmer to manage the contents of [[computer memory]]. Standard C provides no facilities for [[array]] [[bounds checking]] or automatic [[Computer memory garbage collection|garbage collection]]. In contrast, the [[Java programming language|Java]] and [[C Sharp programming language|C#]] languages, both descendants of C, provide automatic [[memory management]], including garbage collection. While manual memory management provides the programmer with greater leeway in tuning the performance of a program, it also makes it easy to produce [[computer bug|bugs]] involving erroneous memory operations, such as [[buffer overflow]]s. Bugs of these sort have gained notoriety for their effects on [[computer insecurity]]. Some tools have been created to help C programmers avoid memory errors, including libraries for performing array [[bounds checking]] and [[automatic garbage collection]], and automated source code checkers such as [[lint programming tool|Lint]].


* <code>struct</code> data types
Some of the specific features of C are:
* <code>long int</code> data type
* <code>unsigned int</code> data type
* The <code>=+</code> operator was changed to <code>+=</code> to remove the semantic ambiguity created by the construct <code>i=+10</code>, which could be interpreted as either <code>i&nbsp;=+&nbsp;10</code> or <code>i&nbsp;=&nbsp;+10</code>.


K&R C is often considered the most basic part of the language that is necessary for a C compiler to support. For many years, even after the introduction of ANSI C, it was considered the "lowest common denominator" that C programmers stuck to when maximum portability was desired, since not all compilers were updated to fully support ANSI C, and reasonably well-written K&R C code is also legal ANSI C.
* An extremely simple [[core language]], with non-essential functionality provided by a standardized set of [[Library (computer science)|library routines]].
* Focus on the [[procedural programming]] paradigm, with facilities for programming in a [[Structured programming|structured style]].
* Use of a [[preprocessor]] language, the [[C preprocessor]], for tasks such as defining [[macro]]s and including multiple [[source code]] files.
* [[Big O notation|O(1) performance]] for all operators.
* Low-level access to [[computer memory]] via the use of [[pointer]]s.
* [[Parameter (computer science)|Parameter]]s are always passed to functions by value, never by reference.
* [[Lexical variable scoping]] (but no support for [[Closure (programming)|closures]] or functions defined within functions).


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.
== History ==


Example call requiring previous declaration:
=== Early developments ===
<pre><nowiki>
long int SomeFunction();


int CallingFunction()
The initial development of C occurred at [[AT&T]] [[Bell Labs]] between [[1969]] and [[1973]]; according to Ritchie, the most creative period occurred in [[1972]]. It was named "C" because many of its features were derived from an earlier language called "[[B programming language|B]]". Accounts differ regarding the origins of the name "B": [[Ken Thompson]] credits the [[BCPL]] programming language, but he had also created a language called [[Bon (programming language)|Bon]] in honor of his wife Bonnie.
{
long int ret;
ret = SomeFunction();
}</nowiki></pre>


Example call not requiring previous declaration:
By [[1973]], the C language had become powerful enough that most of the [[UNIX]] [[kernel (computers)|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 being the [[Multics]] system (written in [[PL/I programming language|PL/I]]) and [[TRIPOS]] (written in BCPL.)
<pre><nowiki>
int CallingFunction()
{
int ret;
ret = SomeOtherFunction();
}


int SomeOtherFunction()
=== K&amp;R C ===
{
return 0;
}
</nowiki></pre>


Since the K&R prototype did not include any information about function arguments, function parameter [[type checking|type checks]] were not performed, although some compilers would issue a warning message if a function was called with the wrong number of arguments.
In [[1978]], Ritchie and [[Brian Kernighan]] published the first edition of ''[[The C Programming Language]]''. This book, known to C programmers as "K&amp;R", served for many years as an informal [[specification]] of the language. The version of C that it describes is commonly referred to as "K&amp;R C." (The second edition of the book covers the later [[ANSI C]] standard, described below.)


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:
K&amp;R introduced the following features to the language:

* <code>struct</code> data types
* <code>long int</code> data type
* <code>unsigned int</code> data type
* The <code>=+</code> operator was changed to <code>+=</code>, and so forth (<code>=+</code> was confusing the C compiler's lexical analyzer).

K&amp;R C is often considered the most basic part of the language that is necessary for a C compiler to support. For many years, even after the introduction of ANSI C, it was considered the "lowest common denominator" that C programmers stuck to when maximum portability was desired, since not all compilers were updated to fully support ANSI C, and reasonably well-written K&amp;R C code is also legal ANSI C.

In the years following the publication of K&amp;R C, several "unofficial" features were added to the language, supported by compilers from AT&amp;T and some other vendors. These included:


* <code>void</code> functions and <code>void *</code> data type
* <code>void</code> functions and <code>void *</code> data type
* functions returning <code>struct</code> or <code>union</code> types
* functions returning <code>struct</code> or <code>union</code> types (rather than pointers)
* [[assignment (computer science)|assignment]] for <code>struct</code> data types
* <code>struct</code> field names in a separate name space for each struct type
* assignment for <code>struct</code> data types
* <code>const</code> qualifier to make an object read-only
* <code>const</code> qualifier to make an object read-only
* a [[C standard library|standard library]] incorporating most of the functionality implemented by various vendors
* a [[C standard library|standard library]] incorporating most of the functionality implemented by various vendors
* [[enumeration]]s
* enumerations
* the single-precision <code>float</code> type


=== ANSI C and ISO C ===
===ANSI C and ISO C===
[[Image:kr_c_prog_lang.jpg|thumb|right|''The C Programming Language'', 2nd edition, is a widely used reference on ANSI C.]]
During the late 1970s, C began to replace [[BASIC programming language|BASIC]] as the leading [[microcomputer]] programming language. During the 1980s, it was adopted for use with the [[IBM PC]], and its popularity began to increase significantly.
At the same time, [[Bjarne Stroustrup]] and others at Bell Labs began work on adding object-oriented programming language constructs to C.
The language they produced, called [[C++]], is now the most common application programming language on the [[Microsoft Windows]] operating system; C remains more popular in the Unix world. Another language developed around that time is [[Objective-C]] which also adds object oriented programming to C. While, now, not as popular as C++, it is used to develop [[Mac OS X]]'s [[Cocoa (API)|Cocoa]] applications.


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).
During the late [[1970s]], C began to replace [[BASIC]] as the leading [[microcomputer]] programming language. During the [[1980s]], it was adopted for use with the [[IBM PC]], and its popularity began to increase significantly. At the same time, [[Bjarne Stroustrup]] and others at Bell Labs began work on adding object-oriented programming language constructs to C. The language they produced, called [[C Plus Plus|C++]], is now the most common application programming language on the [[Microsoft Windows]] operating system; C remains more popular in the Unix world.


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.
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]]. In [[1990]], the ANSI C standard (with a few minor modifications) was adopted by the [[International Standards Organization]] (ISO) as [[ISO 9899|ISO/IEC 9899:1990]].


One of the aims of the ANSI C standardization process was to produce a [[superset]] of K&amp;R C, incorporating many of the unofficial features subsequently introduced. However, the standards committee also included several new features, such as [[function prototype]]s (borrowed from C++), and a more capable [[preprocessor]].
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 prototype]]s (borrowed from C++), and a more capable preprocessor. The syntax for parameter declarations was also changed to reflect the C++ style:


<pre>
ANSI C is now supported by almost all the widely used compilers. Most of the C code being written nowadays is based on ANSI C. Any program written ''only'' in standard C is guaranteed to perform correctly on any [[system platform|platform]] with a conforming C implementation. However, many programs have been written that will only compile on a certain platform, or with a certain compiler, due to (i) the use of non-standard libraries, e.g. for [[Graphical user interface|graphical displays]], and (ii) some compilers not adhering to the ANSI C standard, or its successor, in their default mode.
int main(argc, argv)
int argc;
char *argv[];
{
...
}
</pre>


became
=== C99 ===
<pre>
int main(int argc, char *argv[])
{
...
}
</pre>


ANSI C is now supported by almost all the widely used compilers. Most of the C code being written nowadays is based on ANSI C. Any program written ''only'' in standard C is guaranteed to perform correctly on any [[system platform|platform]] with a conforming C implementation. However, many programs have been written that will only compile on a certain platform, or with a certain compiler, due to (i) the use of non-standard libraries, such as for [[Graphical user interface|graphical displays]], and (ii) some compilers' not adhering to the ANSI C standard, or its successor, in their default mode, or (iii) reliance on the exact size of certain datatypes as well as on the [[endian]]ness of the platform.
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]].

The __STDC__ macro can be used to split code into ANSI and K&R sections.
<pre><nowiki>
#if __STDC__
extern int getopt(int,char * const *,const char *);
#else
extern int getopt();
#endif
</nowiki></pre>

Some suggest using "#if __STDC__", like above, over "#ifdef __STDC__" because some compilers set __STDC__ to zero to indicate non-ANSI compliance.

===C99===
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.


The new features in C99 include:
The new features in C99 include:


* [[inline function]]s
* [[inline function]]s
* [[variable]]s can be declared anywhere (as in C++), rather than only after another declaration or the start of a compound statement
* freeing of restrictions on the location of [[variable declaration]]s (as in C++)
* addition of several new [[data type]]s, including <code>long long int</code> (to reduce the pain of the looming [[32-bit]] to [[64-bit]] transition), an explicit [[Boolean algebra|boolean]] data type, and a <code>complex</code> type representing [[complex number]]s
* several new [[data type]]s, including <code>long long int</code> (to reduce the pain of the looming [[32-bit]] to [[64-bit]] transition), an explicit [[Boolean datatype|boolean]] data type, and a <code>complex</code> type representing [[complex number]]s
* variable-length arrays
* variable-length [[array]]s
* official support for one-line comments beginning with <code>//</code>, borrowed from C++
* support for one-line comments beginning with <code>//</code>, like in [[BCPL]] or C++, and which many C compilers have previously supported as an extension
* several new library functions, such as <code>snprintf()</code>
* several new library functions, such as <code>snprintf()</code>
* several new [[header file]]s, such as <code>stdint.h</code>
* several new [[header file]]s, such as <code>stdint.h</code>


Interest in supporting the new C99 features appears to be mixed. Whereas [[GNU Compiler Collection|GCC]] and several other compilers now support most of the new features of C99, the compilers maintained by [[Microsoft]] and [[Borland]] do not, and these two companies do not seem to be interested in adding such support.
Interest in supporting the new C99 features appears to be mixed. Whereas [[GNU Compiler Collection|GCC]] and several other compilers now support most of the new features of C99, the compilers maintained by [[Microsoft]] and [[Borland]] do not, and these two companies do not seem to be interested in adding such support. Said Microsoft's Brandon Bray, "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++." [http://msdn.microsoft.com/chats/transcripts/vstudio/vstudio_022703.aspx]


==Philosophy==
== "Hello, World!" in C ==
C is a relatively minimalistic [[programming language]]. Among its design goals was that it be straightforwardly compilable by a single pass compiler — that is, that just a few [[machine language]] instructions would be required for each of its core language elements, without extensive [[Runtime|run-time support]]. A single pass compiler is one that can compile a source program without having to search backwards in the source file. This is why a prototype is required if a call to a function appears before its definition. It is quite possible to write C code at a low level of abstraction analogous to [[assembly language]]; in fact C is sometimes referred to (and not always pejoratively) as "high-level assembly" or "portable assembly".


In part due to its relatively 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 [[porting|portably]] written C program can therefore be compiled for a very wide variety of computers.
The following simple application prints out "[[hello world program|Hello, World!]]" to the [[standard output]] file (which is usually the screen, but might be a file or some other hardware device). A version of this program appeared for the first time in K&amp;R.


C was originally developed (along with the [[Unix|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 use in contexts far beyond its initial [[System programming|systems-programming]] roots.
<pre>

<nowiki>
C has the following important features:
#include <stdio.h>

* A simple [[core language]], with important functionality such as math functions and file handling provided by sets of [[Library (computer science)|library routines]] instead
* Focus on the [[procedural programming]] paradigm, with facilities for programming in a [[Structured programming|structured style]]
* A [[type system]] which prevents many operations that are not meaningful
* Use of a [[preprocessor]] language, the [[C preprocessor]], for tasks such as defining [[macro]]s and including multiple [[source code]] files
* Low-level access to [[computer memory]] via the use of [[pointer]]s
* A minimalistic set of keywords
* [[Parameter (computer science)|Parameter]]s that are passed by value. Pass-by-reference semantics may be simulated by explicitly passing [[pointer]] values.
* Function pointers, which allow for a rudimentary form of [[Closure (computer science)|closures]] and [[Polymorphism (computer science)|runtime polymorphism]]
* Lexical variable [[scope (programming)|scope]]
* [[Record (computer science)|Record]]s, or user-defined aggregate datatypes (<code>struct</code>s) which allow related data to be combined and manipulated as a whole

Some features that C lacks that are found in other languages include:
* [[Garbage collection (computer science)|Automatic garbage collection]]
* Language support for [[object-oriented programming]]
* [[Closure (computer science)|Closures]]
* [[Nested function]]s, though [[GCC]] has this feature as an extension.
* Compile-time polymorphism in the form of function [[overloading]], [[operator overloading]], and there is only rudimentary language support for [[generic programming]]
* Native support for [[multithreading]] and [[computer networks|networking]] <!-- Better link than computer networks? -->
Although the list of useful features C lacks is long, this has in a way been important to its acceptance, because it allows new compilers to be written quickly for it on new platforms, keeps the programmer in close control of what the program is doing, and allows solutions most natural for the particular platform. This is what often allows C code to run more efficiently than many other languages. Typically only hand-tuned assembly language code runs faster, since it has full control of the machine, but advances in C compilers and new complexity in modern [[Central processing unit|processors]] have gradually narrowed this gap.

==Usage==
One consequence of C's wide acceptance and efficiency is that the compilers, libraries, and interpreters of other higher-level languages are often implemented in C.

===Intermediate language===
C is used as an [[intermediate language]] by some high-level languages ([[Eiffel programming language|Eiffel]], [[Sather]], [[Esterel]]) which do not output [[object file|object]] or [[machine language|machine]] code, but output C source code only, to submit to a C compiler, which then outputs finished object or machine code. This is done to gain portability and [[Optimization (computer science)|optimization]]. C compilers, often many, exist for most or 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, so is not ideal for use as an intermediate language, leading to development of C-based intermediate languages, such as [[C--]]

==Syntax==
:''Main article: [[C syntax]]''

Unlike languages like [[Fortran 77]], C is free-form, allowing programmers to use arbitrary whitespace (rather than rigid lines) in laying out their code. Comments can be included either between the delimiters <code>/*</code> and <code>*/</code>, or (in C99) following <code>//</code> 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 <code>struct</code>, <code>union</code>, and <code>enum</code>, or assign types to and perhaps reserve storage for new variables, usually by writing the type followed by the variable name. Keywords such as <code>char</code> and <code>int</code>, as well as the pointer-to symbol <code>*</code>, specify built-in types. Sections of code are enclosed in braces (<code>{</code> and <code>}</code>) 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 <code>if</code>, <code>else</code>, <code>switch</code>, <code>do</code>, <code>while</code>, and <code>for</code>. Arbitrary jumps are possible with <code>goto</code>. A variety of built-in operators perform primitive arithmetic, logical, comparative, bitwise, and array indexing operations and assignment. Expressions can also call functions, including a large number of standard library functions, for performing many common tasks.

==="hello, world" example===
The following simple application appeared in the first edition of [[The C Programming Language (book)|K&R]], and has become a standard introductory program in most programming textbooks, regardless of language. The program prints out "[[Hello world program|hello, world]]" to [[standard output]], which is usually a terminal or screen display. However, it might be a file or some other hardware device, including the [[bit bucket]], depending on how standard output is mapped at the time the program is executed.
<br><br>
<pre><nowiki>main()
{
printf("hello, world\n");
}</nowiki></pre>

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 [[C programming language#C99 2|C99]] standard, as a return value of type <code>int</code> will no longer be assumed if the source code has not specified otherwise. 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:

<pre><nowiki>#include <stdio.h>


int main(void)
int main(void)
{
{
printf("Hello, World!\n");
printf("hello, world\n");

return 0;
return 0;
}</nowiki></pre>
}
</nowiki>
</pre>


What follows is a line-by-line analysis of the above program:
== Links and references==


<pre>#include <stdio.h></pre>
=== References ===
This first line of the program is a [[preprocessing|preprocessing directive]], <code>#include</code>. 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 <code>stdio.h</code> — which contains the definitions of standard input and output functions — will replace that line. The angle brackets surrounding <code>stdio.h</code> indicate that <code>stdio.h</code> 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 "in-house" headers.
* ''[[The C Programming Language]]'', by [[Brian Kernighan]] and [[Dennis Ritchie]]. Also known as K&amp;R. The original book on C.
** 1st, Prentice-Hall 1978; ISBN 0-131-10163-3. Pre-ANSI C.
** 2nd, Prentice-Hall 1988; ISBN 0-131-10362-8. ANSI C.
* ''The C Standard'', edited by the [[British Standard Institute]]. The official ISO standard (C99) in book form.
** Wiley, 2003; ISBN 0-470-84573-2.
* ''C: A Reference Manual'', by [[Samuel P. Harbison]] and [[Guy L. Steele]]. This book is excellent as a definitive [[reference manual]], and for those working on C [[compiler]] and [[processor]]s. The book contains a [[Backus-Naur_form|BNF]] grammar for C.
** 4th, Prentice-Hall 1994; ISBN 0-133-26224-3.
** 5th, Prentice-Hall 2002; ISBN 0-130-89592-X.


<pre>int main(void)</pre>
=== See also ===
This next line indicates that a function named <code>main</code> is being defined. The <code>[[main function (programming)|main]]</code> 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 <code>int</code> indicates that the ''return value'' — the value to which the <code>main</code> function will evaluate — is an integer. The portion that reads <code>(void)</code> indicates that the <code>main</code> function takes no arguments. See also [[Void return type|void]].
* [[Anatomy of C program]]
* [[C library]]
* [[C standard library]] ([[ANSI C standard library]])
* [[GNU Compiler Collection]]
* [[make]]


<pre>{</pre>
=== External links ===
This opening curly brace indicates the beginning of the definition of the <code>main</code> function.
*[http://cm.bell-labs.com/cm/cs/who/dmr/chist.html ''The Development of the C Language'' by Dennis M. Ritchie]
*[http://www.lysator.liu.se/c/bwk-tutor.html ''Programming in C: A Tutorial'' by Brian W. Kernighan]
*[http://www.lysator.liu.se/c/ Lysator collection of C language resources]
*[http://www.faqs.org/faqs/C-faq/faq/index.html ''comp.lang.c Answers to Frequently Asked Questions (FAQ List)'' by Steve Summit]
*[http://splint.org/ Splint - Secure Programming Lint - First Aid for Programmers]


<pre> printf("hello, world\n");</pre>
''An early version of this article contained material from [[FOLDOC]], used with [[Public Domain Resources/Foldoc license|permission]].''
This line ''calls'' — looks up and then executes the code for — a function named <code>[[printf]]</code>, which was declared in the included header <code>stdio.h</code>. In this call, the <code>printf</code> function is ''passed'' — provided with — a single argument, the address of the first character in the string literal <code>"hello, world\n"</code>. The sequence that reads <code>\n</code> is an ''escape sequence'' that is translated to the EOL—or end-of-line—character, which is intended to move the output device's current position indicator to the beginning of the next line. The return value of the <code>printf</code> function is of type <code>int</code>, but no use was made of it so it will be quietly discarded.

<pre> return 0;</pre>
This line terminates the execution of the <code>main</code> function and causes it to return the integral value 0.

<pre>}</pre>
This closing curly brace indicates the end of the code for the <code>main</code> function.

If the above code were compiled and executed, it would do the following:

*Print the string "hello, world" onto the standard output device (typically but not always a terminal),
*Move the current position indicator to the beginning of the next line,
*Then return the integer zero to the application's executor.

===Data structures===
C has a [[type system]] similar to that of other [[ALGOL]] descendants such as [[Pascal programming language|Pascal]], although different in a number of ways. There are primitive types for integers of various sizes, both signed and unsigned, [[floating-point number]]s, characters, and enumerated types (<code>enum</code>). There are also derived types including [[array]]s, [[pointer]]s, [[record (computer science)|records]] (<code>struct</code>), and untagged [[union (computer science)|union]]s (<code>union</code>).

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 ''[[Cast (computer science)|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.)

====Pointers====
C makes extensive use of pointers, a very simple type of [[reference (computer science)|reference]] that records, in effect, the address or location of an object in memory. Pointers can be ''dereferenced'' to access the data stored at the underlying address. Pointers can be freely manipulated, using normal assignments and also [[pointer arithmetic]]. The run-time representation of a pointer value is typically a raw memory address, but at compile time, a pointer variable's type includes the type of the data pointed to, which allows expressions including pointers to be type-checked. Pointers are used for many different purposes in C. [[String (computer science)|Text strings]] are commonly manipulated using pointers into<!-- yes, "into" --> arrays of characters. [[Dynamic memory allocation]], which is described below, is performed using pointers. It is also possible to use pointers to functions.

A ''[[null pointer]]'' is a pointer value that points to no valid location. (Dereferencing a null pointer is therefore meaningless, and often results in a run-time 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 return from functions that return pointers. Pointers to type <code>void</code> 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, but they can be easily (and in fact implicitly) converted to and from any other object pointer type.

====Arrays====
<!-- 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 the "obvious way", but there are ANSI-conforming implementations that handle these things in other ways. -->
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. 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 uses recursion within the type system to declare arrays of arrays, which accomplishes approximately the same thing. The index values of the resulting "multidimensional array" can be thought of as flowing in [[row-major order]]. There are provisions for accessing the whole array or elements of the array. Because of the recursive nature of the type system that means that sub-array access is limited to row-by-row access.

====Unification of arrays and pointers====
A unique (and sometimes confusing) feature of C is its treatment of arrays and pointers.
The array-subscript notation <code>x[i]</code> can also be used when <code>x</code> is a pointer; the interpretation (using pointer arithmetic) is to access the <code>(i+1)</code>th of several adjacent data objects pointed to by <code>x</code>, counting the object that <code>x</code> points to (which is <code>x[0]</code>) as the first element of the array.

Formally, <code>x[i]</code> is equivalent to <code>*(x + i)</code>. Since the type of the pointer involved is known to the compiler at compile time, the address that <code>x + i</code> points to is ''not'' the address pointed to by <code>x</code> incremented by <code>i</code>, but rather incremented by <code>i</code> multiplied by the size of the objects that <code>x</code> points to. The size of these objects can be determined with the operator <code>sizeof<code> applied to the pointee of pointer <code>x</code> like in <code>n = sizeof *x</code>. Furthermore, since the operator <code>+</code> is commutative, <code>x + i</code> is equivalent to <code>i + x</code>, so as a consequence <code>x[i]</code> and <code>i[x]</code> and even <code>"textstring"[5]</code> and <code>5["textstring"]</code> are equivalent, too. Due to this handling of pointers in expressions <code>x</code> and <code>i</code> can change places as the programmer likes them to, without changing the meaning of the expressions or the behaviour of the program.

Also, when the name of an array is used in an expression without the subscript (<code>[...]</code>), a pointer to the array's first element is automatically derived and used thereafter: this means that arrays are never copied as a whole when passed as arguments to functions; only the address of its first element is passed.
(A consequence is that although C's function calls use [[call-by-value|pass-by-value]] semantics, arrays seem to be passed by [[Reference (computer science)|reference]].)

===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 distinct ways to allocate memory for objects:
* [[Static memory allocation]]: space for the object is provided in the binary at compile-time; these objects have an [[Variable#Scope and extent|extent]] (or lifetime) as long as the binary which contains them exists
* [[Automatic memory allocation]]: temporary objects can be stored on the [[stack (computing)|stack]], and this space is automatically freed and reusable after the block they are declared in is left
* [[Dynamic memory allocation]]: blocks of memory of any desired size can be requested at run-time using library functions such as <code>[[malloc|malloc()]]</code> from a region of memory called the [[dynamic memory allocation|heap]]; these blocks are reused after the library function <code>[[malloc|free()]]</code> is called on them

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 only known 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 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).

==Criticism==
A popular saying, repeated by such notable language designers as [[Bjarne Stroustrup]], is that "C makes it easy to shoot yourself in the foot" [http://www.research.att.com/~bs/bs_faq.html#really-say-that] In other words, C permits many operations that are generally not desirable, and thus many simple errors made by a programmer are not detected by the compiler or even when they occur at runtime. This leads to programs with unpredictable behavior and security holes. In other words, "C is a sharp tool". It is certainly not a language for beginners in programming. The safe C dialect [[Cyclone programming language|Cyclone]] addresses some of these problems.

Part of the reason for this is to avoid compile- and run-time checks that were too expensive when C was originally designed. Another reason is the desire to keep C as efficient and flexible as possible; the more powerful a language, the more difficult it is to prove things about programs written in it. Some checks were also relegated to external tools, 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.

===Memory allocation===
One issue to be aware of when using C is that automatically and dynamically allocated objects are not initialized; they initially have an indeterminate value (typically whatever value is present in the memory space they occupy, which might not even be a legal bitpattern for that type). This value is highly unpredictable and can vary between two machines, two program runs, or even two calls to the same function. If the program attempts to use such an uninitialized value, the results are undefined. Many modern compilers try to detect and warn about this problem, but both false positives and false negatives occur.

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. If the lifetime of the last pointer accessible by a live program variable ends (an auto pointer going out of scope, or being overwritten for example) and is referencing a particular allocation that is not freed via a call to <code>free()</code> then that memory cannot be recovered for later reuse and is essentially lost to the program. This is called a ''[[memory leak]]''. Conversely, it is possible to release memory too soon, and then continue 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 in parts of the program that are different from where the erroneous operations actually occured). These issues in particular are ameliorated in languages with [[garbage collection (computer science)|automatic garbage collection]] or [[resource acquisition is initialization|RAII]].

===Pointers===
Pointers are a primary source of danger. Because they are typically unchecked, a pointer can be made to point to any arbitrary location (even within code), causing unpredictable effects. Although properly-used pointers point to safe places, they can be moved to unsafe places using pointer arithmetic; the memory they point to may be deallocated and reused ([[dangling pointer]]s); they may be uninitialized ([[wild pointer]]s); or they may be directly assigned a value using a cast, union, or through another corrupt pointer. In general, C is permissive in allowing manipulation of and conversion between pointer types. Other languages attempt to address these problems by using more restrictive [[reference (computer science)|reference]] types.

===Arrays===
Although C has native support for static arrays, it is not required to verify that array indexes are valid ([[bounds checking]]). For example, one can write to the sixth element of an array with five elements, yielding generally undesirable results. This type of bug, called a ''[[buffer overflow]],'' has been notorious as the source of a number of security problems. On the other hand, since [[bounds checking elimination]] technology was largely nonexistent when C was defined, bounds checking came with a severe performance penalty, particularly in numerical computation. It is also, arguably, inconsistent with C's minimalist approach. (Actually, the decision to equate an array with a pointer to its first element, and to use this approach for passing arrays as function parameters -- without bounds information, pretty much ruled out [[bounds checking]] from the beginning.)

Multidimensional arrays are necessary in numerical algorithms (mainly from applied linear algebra) to store matrices. The structure of the C array is very well adapted and fit for this particular task, provided one is prepared to count one's indices from 0 instead of 1. This issue is discussed in the book ''Numerical Recipes in C'', Chap. 1.2, page 20 ff ([http://www.library.cornell.edu/nr/bookcpdf/c1-2.pdf read online]). In that book there is also a solution based on negative addressing which introduces other dangers.

===Variadic functions===

Another source of bugs is [[variadic function]]s, which take a variable number of arguments. Unlike other prototyped C functions, checking the types of arguments to variadic functions at compile-time is impossible in general without additional information. If the wrong type of data is passed, the effect is unpredictable, and often fatal. Variadic functions also handle null pointer constants in a way which is often suprising to those unfamiliar with the language semantics. For example, NULL must be cast to the desired pointer type when passed to a variadic function. The [[printf]] family of functions supplied by the standard library, used to generate formatted text output, has been noted for its error-prone variadic interface, which relies on a format string to specify the number and type of trailing arguments.

Type-checking of variadic functions from the standard library is a quality of implementation issue, however, and many modern compilers do in particular type-check <code>printf</code> calls, producing warnings if the argument list is inconsistent with the format string. However, not all printf calls can be checked statically, since the format string can be built at runtime, and other variadic functions typically remain unchecked.

===Syntax===
Although mimicked by many languages because of its widespread familiarity, C's syntax has been often targeted as one of its weakest points. For example, Kernighan and Ritchie say in the second edition of ''The C Programming Language'', "C, like any other language, has its blemishes. Some of the operators have the wrong precedence; some parts of the syntax could be better." Bjarne Stroustrup has also derided C++'s syntax, which is very similar to that of 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] Some specific problems worth noting are:

* A function prototype with an empty parameter list allows any set of parameters, a syntax problem introduced for backward compatibility with K&R C, which lacked prototypes.
* Some questionable choices of operator precedence, as mentioned by Kernighan and Ritchie above, such as <code>==</code> binding more tightly than <code>&</code> and <code>|</code> in expressions like <code>x & 1 == 0</code>.
* The use of the <code>=</code> operator, used in mathematics for equality, to indicate assignment, leading to unintended assignments in comparisons and a false impression that assignment is transitive. Having <code>=</code> denote assignment and <code>==</code> equality was a deliberate decision by Ritchie, who noted that assignment occurs much more often than comparisons.
* A lack of [[infix]] operators for complex objects, particularly for string operations, making programs which rely heavily on these operations difficult to read.
* Heavy reliance on punctuation-based symbols even where this is arguably less clear, such as "&&" and "||" instead of "and" and "or" (though "and" and "or" are theoretically available as alternatives with the inclusion of a certain header).
* The un-intuitive declaration syntax, particularly for function pointers. In the words of language researcher [[Damian Conway]] speaking about the very similar C++ declaration syntax:
::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. [http://www.csse.monash.edu.au/~damian/papers/HTML/ModestProposal.html#section3.1.1 A Modest Proposal: C++ Resyntaxed]. Section 3.1.1. 1996.''

===Maintenance===
There are other problems in C that don't directly result in bugs or errors, but make it harder for inexperienced programmers to build a robust, maintainable, large-scale system. Examples of these include:
* A fragile system for importing definitions (<code>#include</code>) that relies on literal text inclusion and redundantly keeping prototypes and function definitions in sync, and drastically increases build times.
* A cumbersome compilation model that forces manual dependency tracking and inhibits [[compiler optimization]]s between modules (except by [[link-time optimization]]).
* A weak type system that lets many clearly erroneous programs compile without errors.

===Compiler-external static-checking tools===
Tools have been created to help C programmers avoid these errors in many cases.

Automated source code checking and auditing is fruitful in any language, and for C many such tools exist such as [[lint programming tool|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 [[garbage collection (computer science)|automatic garbage collection]], that are not a standard part of C.

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 conjuction 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-bound 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.

==Related languages==
===C++===
The [[C++]] programming language was originally derived from C. However, not every C program is a valid C++ program. As C and C++ have evolved independently, there has been an increase in the number of incompatibilities between the two languages [http://david.tribble.com/text/cdiffs.htm]. The latest revision of C, C99, created a number of additional conflicting features. The differences make it hard to write programs and libraries that are compiled and function correctly as either C or C++ code, and confuse those who program in both languages. The disparity also makes it hard for either language to adopt features from the other one.

[[Bjarne Stroustrup]], the creator of C++, has repeatedly suggested [http://www.research.att.com/~bs/sibling_rivalry.pdf] that the incompatibilities between C and C++ should be reduced as much as possible in order to maximize inter-operability between the two languages. Others have argued that since C and C++ are two different languages, compatibility between them is useful but not vital; according to this camp, efforts to reduce incompatibility should not hinder attempts to improve each language in isolation.

Today, the primary differences (as opposed to the additions of C++, such as classes, templates, namespaces, overloading) between the two languages are:
* <code>'''inline'''</code> — [[inline function]]s are in the global scope in C++, and in the file (so-called "static") scope in C. In simple terms, this means that in C++, any definition of any inline function (but irrespective of C++ function overloading) must conform to C++'s "[[One Definition Rule]]" or ODR, requiring that either there be a single definition of any inline function or that all definitions be semantically equivalent; but that in C, the same inline function could be defined differently in different ''translation units'' (translation unit typically refers to a [[Computer file|file]]). (Note that Microsoft C++ compilers define inline functions as C99 ones)
* The <code>'''bool'''</code> type in C99 is in its own header, <code>'''<stdbool.h>'''</code>. Previous C standards did not define a boolean type, and various (incompatible) methods were used to simulate a boolean type.
* Single character constants (enclosed in single quotes) have the size of an <code>int</code> in C and a <code>char</code> in C++. So in C <code>sizeof 'a' == sizeof(int)</code> whereas in C++ <code>sizeof 'a' == sizeof(char)</code>. Nevertheless, even in C they will never exceed the values that a <code>char</code> can store, so <code>(char)'a'</code> is a safe conversion that will only change the type of the expression (here it is changed from int to char), but not its value (which on systems using ASCII-encoded characters is 97).
* Additional keywords were introduced in C++, and thus they cannot be used as identifiers as they could in C. (for example, <code>try</code>, <code>catch</code>, <code>template</code>, <code>new</code>, <code>delete</code>, ...)
* In C++, the compiler automatically creates a "tag" for every <code>struct</code>, <code>union</code> or <code>enum</code>, so <code>struct S {};</code> in C++ is equivalent to <code>typedef struct S {} S;</code> in C.

C99 adopted some features that first appeared in C++. Among them are:
* Mandatory prototype declarations for functions
* The <code>'''inline'''</code> keyword
* The removal of the "implicit int" return value

==See also==
*[[C preprocessor]]
*[[C standard library]]
*[[C library]]
*[[C string]]
*[[C syntax]]
*[[C variable types and declarations]]
*[[List of articles with C programs]]
*[[Objective-C]]
*[[C++]]
*[[Operators in C and C++]]
*[[Programming tool]]s: [[Cygwin]], [[Dev-C/C++]], [[DJGPP]], [[GNU Compiler Collection]], [[Local C compiler|LCC]], [[Linker]], [[make]], [[SPlint]], [[Small-C]], [[C--|C--]]
*[[Pascal and C]]

==References==
* [[Brian Kernighan]], [[Dennis Ritchie]]: ''[[The C Programming Language (book)|The C Programming Language]]''. Also known as K&R — The original book on C.
**1st, Prentice Hall 1978; ISBN 0-131-10163-3. Pre-ANSI C.
**2nd, Prentice Hall 1988; ISBN 0-131-10362-8. ANSI C.
* [http://www.open-std.org/JTC1/SC22/WG14/www/standards ISO/IEC 9899]. The official C:1999 standard, along with defect reports and a rationale. As of 2005 the latest version is [http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf ISO/IEC 9899:TC2].
*[[Samuel P. Harbison]], [[Guy L. Steele]]: ''C: A Reference Manual''. This book is excellent as a definitive reference manual, and for those working on C [[compiler]]s. The book contains a [[Backus-Naur form|BNF]] grammar for C.
**4th, Prentice Hall 1994; ISBN 0-133-26224-3.
**5th, Prentice Hall 2002; ISBN 0-130-89592-X.
*[[Derek M. Jones]]: ''The New C Standard: A Cultural and Economic Commentary'', Addison-Wesley, ISBN 0-201-70917-1, [http://www.knosof.co.uk/cbook/cbook.html online material]
*[[Robert Sedgewick (computer scientist)|Robert Sedgewick]]: ''Algorithms in C'', Addison-Wesley, ISBN 0-201-31452-5 (Part 1–4) and ISBN 0-201-31663-3 (Part 5)
* William H. Press, Saul A. Teukolsky, William T. Vetterling, Brian P. Flannery: [[Numerical Recipes]] in C (The Art of Scientific Computing), ISBN 0-521-43108-5

==External links==
{{Wikibooks}}

===Tutorials===
* [http://www.its.strath.ac.uk/courses/c/ C Programming] (course at University of Strathclyde Computer Centre)
* [http://publications.gbdirect.co.uk/c_book/ The C Book] by M.Banahan-D.Brady-M.Doran (Addison-Wensley, 2nd ed.) — A very interesting and complete book for beginners/intermediate, now off-print and free.
* [http://users.powernet.co.uk/eton/unleashed/ C Unleashed] by Richard Heathfield and others contributors in c.l.c (Sams) — An interesting book about advanced ISO-C. Full of tricks and good practices.

===Resources===
* [http://www.open-std.org/jtc1/sc22/wg14/ Official web site] of the ISO C Working Group
* [http://c-faq.com/ comp.lang.c Frequently Asked Questions]
* [http://clc-wiki.net/wiki/Main_Page comp.lang.c Wiki]
* [http://www.lysator.liu.se/c/ Programming in C] (document collection at Lysator)
* [http://www.coding-guidelines.com/cbook/cbook1_0b.pdf ''The New C Standard: An economic and cultural commentary''] — an unpublished book about "detailed analysis of the International Standard for the C language"

===Optimization Techniques===
*[http://www.eventhelix.com/RealtimeMantra/Basics/OptimizingCAndCPPCode.htm C,C++ optimization]
*[http://www.azillionmonkeys.com/qed/optimize.html Programming Optimization]
*[http://www.abarnett.demon.co.uk/tutorial.html C optimization tutorial]

===C99===
* [http://www-106.ibm.com/developerworks/linux/library/l-c99.html?ca=dgr-lnxw07UsingC99 Open source development using C99 — Is your C code up to standard?] by [[Peter Seebach]]
*[http://www.kuro5hin.org/?op=displaystory;sid=2001/2/23/194544/139 Are you Ready For C99?]
*Article "[http://david.tribble.com/text/cdiffs.htm Incompatibilities Between ISO C and ISO C++]" by [[David R. Tribble]]

===Support===
* [http://cboard.cprogramming.com/forumdisplay.php?f=4 C Forum] at Cprogramming.com
* [http://www.daniweb.com/techtalkforums/forum8.html C and C++] at Daniweb

===History===
* [http://cm.bell-labs.com/cm/cs/who/dmr/chist.html ''The Development of the C Language''] by [[Dennis M. Ritchie]]

===Miscellaneous===
* [http://www.ioccc.org International Obfuscated C Code Contest]

{{Major programming languages small}}

[[Category:C programming language| ]]
[[Category:Programming languages]]
[[Category:Curly bracket programming languages]]

[[an:Luengache de pogramazión C]]
[[ar:سي]]
[[az:C]]
[[ast:Llinguaxe de programación C]]
[[be:C (мова праграмавання)]]
[[bg:C (език за програмиране)]]
[[bs:C programski jezik]]
[[ca:Llenguatge C]]
[[cs:C (programovací jazyk)]]
[[da:C (programmeringssprog)]]
[[de:C (Programmiersprache)]]
[[eo:C (programlingvo)]]
[[es:Lenguaje de programación C]]
[[et:C (programmeerimiskeel)]]
[[eu:C programazio lenguaia]]
[[fi:C (ohjelmointikieli)]]
[[fr:C (langage)]]
[[gl:Linguaxe de programación C]]
[[he:C (שפת תכנות)]]
[[hr:C (programski jezik)]]
[[hu:C programozási nyelv]]
[[id:Bahasa pemrograman C]]
[[is:Forritunarmálið C]]
[[it:C (linguaggio)]]
[[ja:C言語]]
[[ko:C 프로그래밍 언어]]
[[lt:C (kalba)]]
[[lv:C (programmēšanas valoda)]]
[[ms:Bahasa pengaturcaraan C]]
[[nl:C (programmeertaal)]]
[[no:C (programmeringsspråk)]]
[[pl:C (język programowania)]]
[[pt:Linguagem de programação C]]
[[ro:Limbajul C]]
[[ru:Си (язык программирования)]]
[[simple:C programming language]]
[[sk:C (programovací jazyk)]]
[[sl:Programski jezik C]]
[[sq:Gjuha programuese C]]
[[sv:C (programspråk)]]
[[th:ภาษาซี]]
[[tr:C programlama dili]]
[[uk:Мова програмування C]]
[[vi:C (ngôn ngữ lập trình)]]
[[zh:C语言]]

Revision as of 09:26, 21 January 2006

File:K&R C.jpg
The C Programming Language, Brian Kernighan and Dennis Ritchie, the original edition that served for many years as an informal specification of the language

The C programming language is a standardized 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 one of the most widely used programming languages. C is prized for its efficiency, and is the most popular programming language for writing system software, though it is also used for writing applications. It is also commonly used in computer science education, despite not being designed for novices.

History

Early developments

The initial development of C occurred at AT&T Bell Labs between 1969 and 1973; according to Ritchie, the most creative period occurred in 1972. It was named "C" because many of its features were derived from an earlier language called "B". Accounts differ regarding the origins of the name "B": Ken Thompson credits the BCPL programming language, but he had also created a language called Bon in honor of his wife Bonnie.

There are many legends as to the origin of C and its related operating system, Unix, including:

  • The development of C was the result of the programmers' desire to play Space Travel. They had been playing it on their company's mainframe, but being underpowered and having to support about 100 users, Thompson and Ritchie found they didn't have sufficient control over the spaceship to avoid collisions with the wandering space rocks. Thus, they decided to port the game to an idle PDP-7 in the office. But it didn't have an operating system (OS), so they set about writing one. Eventually they decided to port the operating system to the office's PDP-11, but this was onerous since all the code was in assembly language. They decided to use a higher-level portable language so the OS could be ported easily from one computer to another. They looked at using B, but it lacked functionality to take advantage of some of the PDP-11's advanced features. So they set about creating the new language, C.
  • The justification for obtaining the original computer that was used to develop Unix was to create a system to automate the filing of patents. The original version of Unix was developed in assembly language. Later, the C language was developed in order to rewrite the operating system.

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 C

In 1978, Ritchie and Brian Kernighan published the first edition of The C Programming Language. This book, known to C programmers as "K&R", served for many years as an informal specification of the language. The version of C that it describes is commonly referred to as "K&R C." (The second edition of the book covers the later ANSI C standard, described below.)

K&R introduced the following features to the language:

  • struct data types
  • long int data type
  • unsigned int data type
  • The =+ 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 is necessary for a C compiler to support. For many years, even after the introduction of ANSI C, it was considered the "lowest common denominator" that C programmers stuck to when maximum portability was desired, since not all compilers were updated to fully support ANSI C, and reasonably well-written K&R C code is also legal ANSI C.

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
  • functions returning struct or union types (rather than pointers)
  • assignment for struct data types
  • const qualifier to make an object read-only
  • a standard library incorporating most of the functionality implemented by various vendors
  • enumerations

ANSI C and ISO C

File:Kr c prog lang.jpg
The C Programming Language, 2nd edition, is a widely used reference on ANSI C.

During the late 1970s, C began to replace BASIC as the leading microcomputer programming language. During the 1980s, it was adopted for use with the IBM PC, and its popularity began to increase significantly. At the same time, Bjarne Stroustrup and others at Bell Labs began work on adding object-oriented programming language constructs to C. The language they produced, called C++, is now the most common application programming language on the Microsoft Windows operating system; C remains more popular in the Unix world. Another language developed around that time is Objective-C which also adds object oriented programming to C. While, now, not as popular as C++, it is used to develop Mac OS X's Cocoa applications.

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 compilers. Most of the C code being written nowadays is based on ANSI C. Any program written only in standard C is guaranteed to perform correctly on any platform with a conforming C implementation. However, many programs have been written that will only compile on a certain platform, or with a certain compiler, due to (i) the use of non-standard libraries, such as for graphical displays, and (ii) some compilers' not adhering to the ANSI C standard, or its successor, in their default mode, or (iii) reliance on the exact size of certain datatypes as well as on the endianness of the platform.

The __STDC__ macro can be used to split code into ANSI and K&R sections.

#if __STDC__
extern int getopt(int,char * const *,const char *);
#else
extern int getopt();
#endif

Some suggest using "#if __STDC__", like above, over "#ifdef __STDC__" because some compilers set __STDC__ to zero to indicate non-ANSI compliance.

C99

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.

The new features in C99 include:

  • inline functions
  • variables can be declared anywhere (as in C++), rather than only after another declaration or the start of a compound statement
  • several new data types, including long long int (to reduce the pain of the looming 32-bit to 64-bit transition), an explicit boolean data type, and a complex type representing complex numbers
  • variable-length arrays
  • support for one-line comments beginning with //, like in BCPL or C++, and which many C compilers have previously supported as an extension
  • several new library functions, such as snprintf()
  • several new header files, such as stdint.h

Interest in supporting the new C99 features appears to be mixed. Whereas GCC and several other compilers now support most of the new features of C99, the compilers maintained by Microsoft and Borland do not, and these two companies do not seem to be interested in adding such support. Said Microsoft's Brandon Bray, "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++." [1]

Philosophy

C is a relatively minimalistic programming language. Among its design goals was that it be straightforwardly compilable by a single pass compiler — that is, that just a few machine language instructions would be required for each of its core language elements, without extensive run-time support. A single pass compiler is one that can compile a source program without having to search backwards in the source file. This is why a prototype is required if a call to a function appears before its definition. It is quite possible to write C code at a low level of abstraction analogous to assembly language; in fact C is sometimes referred to (and not always pejoratively) as "high-level assembly" or "portable assembly".

In part due to its relatively 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 computers.

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 use in contexts far beyond its initial systems-programming roots.

C has the following important features:

Some features that C lacks that are found in other languages include:

Although the list of useful features C lacks is long, this has in a way been important to its acceptance, because it allows new compilers to be written quickly for it on new platforms, keeps the programmer in close control of what the program is doing, and allows solutions most natural for the particular platform. This is what often allows C code to run more efficiently than many other languages. Typically only hand-tuned assembly language code runs faster, since it has full control of the machine, but advances in C compilers and new complexity in modern processors have gradually narrowed this gap.

Usage

One consequence of C's wide acceptance and efficiency is that the compilers, libraries, and interpreters of other higher-level languages are often implemented in C.

Intermediate language

C is used as an intermediate language by some high-level languages (Eiffel, Sather, Esterel) which do not output object or machine code, but output C source code only, to submit to a C compiler, which then outputs finished object or machine code. This is done to gain portability and optimization. C compilers, often many, exist for most or 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, so is not ideal for use as an intermediate language, leading to development of C-based intermediate languages, such as C--

Syntax

Main article: C syntax

Unlike languages like Fortran 77, C is free-form, allowing programmers to use arbitrary whitespace (rather than rigid lines) in laying out their code. 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, logical, comparative, bitwise, and array indexing operations and assignment. Expressions can also call functions, including a large number of standard library functions, for performing many common tasks.

"hello, world" example

The following simple application appeared in the first edition of K&R, and has become a standard introductory program in most programming textbooks, regardless of language. The program prints out "hello, world" to standard output, which is usually a terminal or screen display. However, it might be a file or some other hardware device, including the bit bucket, depending on how standard output is mapped at the time the program is executed.

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 otherwise. 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 <stdio.h>

int main(void)
{
    printf("hello, world\n");

    return 0;
}

What follows is a line-by-line analysis of the above program:

#include <stdio.h>

This 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 "in-house" 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 portion that reads (void) 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 was 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 sequence that reads \n is an escape sequence that is translated to the EOL—or end-of-line—character, which is intended to move the output device's current position indicator to 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.

}

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:

  • Print the string "hello, world" onto the standard output device (typically but not always a terminal),
  • Move the current position indicator to the beginning of the next line,
  • Then return the integer zero to the application's executor.

Data structures

C has a type system similar to that of other ALGOL descendants such as Pascal, although different in a number of ways. There are primitive types for integers of various sizes, both signed and unsigned, floating-point numbers, characters, and enumerated types (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.)

Pointers

C makes extensive use of pointers, a very simple type of reference that records, in effect, the address or location of an object in memory. Pointers can be dereferenced to access the data stored at the underlying address. Pointers can be freely manipulated, using normal assignments and also pointer arithmetic. The run-time representation of a pointer value is typically a raw memory address, but at compile time, a pointer variable's type includes the type of the data pointed to, which allows expressions including pointers to be type-checked. Pointers are used for many different purposes in C. Text strings are commonly manipulated using pointers into arrays of characters. Dynamic memory allocation, which is described below, is performed using pointers. It is also possible to use pointers to functions.

A null pointer is a pointer value that points to no valid location. (Dereferencing a null pointer is therefore meaningless, and often results in a run-time 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 return 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, but they can be easily (and in fact implicitly) converted to and from any other object pointer type.

Arrays

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. 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 uses recursion within the type system to declare arrays of arrays, which accomplishes approximately the same thing. The index values of the resulting "multidimensional array" can be thought of as flowing in row-major order. There are provisions for accessing the whole array or elements of the array. Because of the recursive nature of the type system that means that sub-array access is limited to row-by-row access.

Unification of arrays and pointers

A unique (and sometimes confusing) feature of C is its treatment of arrays and pointers. The array-subscript notation x[i] can 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[i] 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 pointee of pointer x like in n = sizeof *x. Furthermore, since the operator + is commutative, x + i is equivalent to i + x, so as a consequence x[i] and i[x] and even "textstring"[5] and 5["textstring"] are equivalent, too. Due to this handling of pointers in expressions x and i can change places as the programmer likes them to, without changing the meaning of the expressions or the behaviour of the program.

Also, when the name of an array is used in an expression without the subscript ([...]), a pointer to the array's first element is automatically derived and used thereafter: this means that arrays are never copied as a whole when passed as arguments to functions; only the address of its first element is passed. (A consequence is that although C's function calls use pass-by-value semantics, arrays seem to be passed by reference.)

Memory management

One of the most important functions of a programming language is to provide facilities for managing memory and the objects that are stored in memory. C provides three distinct ways to allocate memory for objects:

  • Static memory allocation: space for the object is provided in the binary at compile-time; these objects have an extent (or lifetime) as long as the binary which contains them exists
  • Automatic memory allocation: temporary objects can be stored on the stack, and this space is automatically freed and reusable after the block they are declared in is left
  • Dynamic memory allocation: blocks of memory of any desired size can be requested at run-time using library functions such as malloc() from a region of memory called the heap; these blocks are reused after the library function free() is called on them

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 only known 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 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).

Criticism

A popular saying, repeated by such notable language designers as Bjarne Stroustrup, is that "C makes it easy to shoot yourself in the foot" [2] In other words, C permits many operations that are generally not desirable, and thus many simple errors made by a programmer are not detected by the compiler or even when they occur at runtime. This leads to programs with unpredictable behavior and security holes. In other words, "C is a sharp tool". It is certainly not a language for beginners in programming. The safe C dialect Cyclone addresses some of these problems.

Part of the reason for this is to avoid compile- and run-time checks that were too expensive when C was originally designed. Another reason is the desire to keep C as efficient and flexible as possible; the more powerful a language, the more difficult it is to prove things about programs written in it. Some checks were also relegated to external tools, 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.

Memory allocation

One issue to be aware of when using C is that automatically and dynamically allocated objects are not initialized; they initially have an indeterminate value (typically whatever value is present in the memory space they occupy, which might not even be a legal bitpattern for that type). This value is highly unpredictable and can vary between two machines, two program runs, or even two calls to the same function. If the program attempts to use such an uninitialized value, the results are undefined. Many modern compilers try to detect and warn about this problem, but both false positives and false negatives occur.

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. If the lifetime of the last pointer accessible by a live program variable ends (an auto pointer going out of scope, or being overwritten for example) and is 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. This is called a memory leak. Conversely, it is possible to release memory too soon, and then continue 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 in parts of the program that are different from where the erroneous operations actually occured). These issues in particular are ameliorated in languages with automatic garbage collection or RAII.

Pointers

Pointers are a primary source of danger. Because they are typically unchecked, a pointer can be made to point to any arbitrary location (even within code), causing unpredictable effects. Although properly-used pointers point to safe places, they can be moved to unsafe places using pointer arithmetic; the memory they point to may be deallocated and reused (dangling pointers); they may be uninitialized (wild pointers); or they may be directly assigned a value using a cast, union, or through another corrupt pointer. In general, C is permissive in allowing manipulation of and conversion between pointer types. Other languages attempt to address these problems by using more restrictive reference types.

Arrays

Although C has native support for static arrays, it is not required to verify that array indexes are valid (bounds checking). For example, one can write to the sixth element of an array with five elements, yielding generally undesirable results. This type of bug, called a buffer overflow, has been notorious as the source of a number of security problems. On the other hand, since bounds checking elimination technology was largely nonexistent when C was defined, bounds checking came with a severe performance penalty, particularly in numerical computation. It is also, arguably, inconsistent with C's minimalist approach. (Actually, the decision to equate an array with a pointer to its first element, and to use this approach for passing arrays as function parameters -- without bounds information, pretty much ruled out bounds checking from the beginning.)

Multidimensional arrays are necessary in numerical algorithms (mainly from applied linear algebra) to store matrices. The structure of the C array is very well adapted and fit for this particular task, provided one is prepared to count one's indices from 0 instead of 1. This issue is discussed in the book Numerical Recipes in C, Chap. 1.2, page 20 ff (read online). In that book there is also a solution based on negative addressing which introduces other dangers.

Variadic functions

Another source of bugs is variadic functions, which take a variable number of arguments. Unlike other prototyped C functions, checking the types of arguments to variadic functions at compile-time is impossible in general without additional information. If the wrong type of data is passed, the effect is unpredictable, and often fatal. Variadic functions also handle null pointer constants in a way which is often suprising to those unfamiliar with the language semantics. For example, NULL must be cast to the desired pointer type when passed to a variadic function. The printf family of functions supplied by the standard library, used to generate formatted text output, has been noted for its error-prone variadic interface, which relies on a format string to specify the number and type of trailing arguments.

Type-checking of variadic functions from the standard library is a quality of implementation issue, however, and many modern compilers do in particular type-check printf calls, producing warnings if the argument list is inconsistent with the format string. However, not all printf calls can be checked statically, since the format string can be built at runtime, and other variadic functions typically remain unchecked.

Syntax

Although mimicked by many languages because of its widespread familiarity, C's syntax has been often targeted as one of its weakest points. For example, Kernighan and Ritchie say in the second edition of The C Programming Language, "C, like any other language, has its blemishes. Some of the operators have the wrong precedence; some parts of the syntax could be better." Bjarne Stroustrup has also derided C++'s syntax, which is very similar to that of C: "Within C++, there is a much smaller and cleaner language struggling to get out. [...] the C++ semantics is much cleaner than its syntax." [3] Some specific problems worth noting are:

  • A function prototype with an empty parameter list allows any set of parameters, a syntax problem introduced for backward compatibility with K&R C, which lacked prototypes.
  • Some questionable choices of operator precedence, as mentioned by Kernighan and Ritchie above, such as == binding more tightly than & and | in expressions like x & 1 == 0.
  • The use of the = operator, used in mathematics for equality, to indicate assignment, leading to unintended assignments in comparisons and a false impression that assignment is transitive. Having = denote assignment and == equality was a deliberate decision by Ritchie, who noted that assignment occurs much more often than comparisons.
  • A lack of infix operators for complex objects, particularly for string operations, making programs which rely heavily on these operations difficult to read.
  • Heavy reliance on punctuation-based symbols even where this is arguably less clear, such as "&&" and "||" instead of "and" and "or" (though "and" and "or" are theoretically available as alternatives with the inclusion of a certain header).
  • The un-intuitive declaration syntax, particularly for function pointers. In the words of language researcher Damian Conway speaking about the very similar C++ declaration syntax:
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.

Maintenance

There are other problems in C that don't directly result in bugs or errors, but make it harder for inexperienced programmers to build a robust, maintainable, large-scale system. Examples of these include:

  • A fragile system for importing definitions (#include) that relies on literal text inclusion and redundantly keeping prototypes and function definitions in sync, and drastically increases build times.
  • A cumbersome compilation model that forces manual dependency tracking and inhibits compiler optimizations between modules (except by link-time optimization).
  • A weak type system that lets many clearly erroneous programs compile without errors.

Compiler-external static-checking tools

Tools have been created to help C programmers avoid these errors in many cases.

Automated source code checking and auditing is fruitful 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.

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 conjuction 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-bound 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++

The C++ programming language was originally derived from C. However, not every C program is a valid C++ program. As C and C++ have evolved independently, there has been an increase in the number of incompatibilities between the two languages [4]. The latest revision of C, C99, created a number of additional conflicting features. The differences make it hard to write programs and libraries that are compiled and function correctly as either C or C++ code, and confuse those who program in both languages. The disparity also makes it hard for either language to adopt features from the other one.

Bjarne Stroustrup, the creator of C++, has repeatedly suggested [5] that the incompatibilities between C and C++ should be reduced as much as possible in order to maximize inter-operability between the two languages. Others have argued that since C and C++ are two different languages, compatibility between them is useful but not vital; according to this camp, efforts to reduce incompatibility should not hinder attempts to improve each language in isolation.

Today, the primary differences (as opposed to the additions of C++, such as classes, templates, namespaces, overloading) between the two languages are:

  • inlineinline functions are in the global scope in C++, and in the file (so-called "static") scope in C. In simple terms, this means that in C++, any definition of any inline function (but irrespective of C++ function overloading) must conform to C++'s "One Definition Rule" or ODR, requiring that either there be a single definition of any inline function or that all definitions be semantically equivalent; but that in C, the same inline function could be defined differently in different translation units (translation unit typically refers to a file). (Note that Microsoft C++ compilers define inline functions as C99 ones)
  • The bool type in C99 is in its own header, <stdbool.h>. Previous C standards did not define a boolean type, and various (incompatible) methods were used to simulate a boolean type.
  • Single character constants (enclosed in single quotes) have the size of an int in C and a char in C++. So in C sizeof 'a' == sizeof(int) whereas in C++ sizeof 'a' == sizeof(char). Nevertheless, even in C they will never exceed the values that a char can store, so (char)'a' is a safe conversion that will only change the type of the expression (here it is changed from int to char), but not its value (which on systems using ASCII-encoded characters is 97).
  • Additional keywords were introduced in C++, and thus they cannot be used as identifiers as they could in C. (for example, try, catch, template, new, delete, ...)
  • In C++, the compiler automatically creates a "tag" for every struct, union or enum, so struct S {}; in C++ is equivalent to typedef struct S {} S; in C.

C99 adopted some features that first appeared in C++. Among them are:

  • Mandatory prototype declarations for functions
  • The inline keyword
  • The removal of the "implicit int" return value

See also

References

  • Brian Kernighan, Dennis Ritchie: The C Programming Language. Also known as K&R — The original book on C.
    • 1st, Prentice Hall 1978; ISBN 0-131-10163-3. Pre-ANSI C.
    • 2nd, Prentice Hall 1988; ISBN 0-131-10362-8. ANSI C.
  • ISO/IEC 9899. The official C:1999 standard, along with defect reports and a rationale. As of 2005 the latest version is ISO/IEC 9899:TC2.
  • Samuel P. Harbison, Guy L. Steele: C: A Reference Manual. This book is excellent as a definitive reference manual, and for those working on C compilers. The book contains a BNF grammar for C.
    • 4th, Prentice Hall 1994; ISBN 0-133-26224-3.
    • 5th, Prentice Hall 2002; ISBN 0-130-89592-X.
  • Derek M. Jones: The New C Standard: A Cultural and Economic Commentary, Addison-Wesley, ISBN 0-201-70917-1, online material
  • Robert Sedgewick: Algorithms in C, Addison-Wesley, ISBN 0-201-31452-5 (Part 1–4) and ISBN 0-201-31663-3 (Part 5)
  • William H. Press, Saul A. Teukolsky, William T. Vetterling, Brian P. Flannery: Numerical Recipes in C (The Art of Scientific Computing), ISBN 0-521-43108-5

Tutorials

  • C Programming (course at University of Strathclyde Computer Centre)
  • The C Book by M.Banahan-D.Brady-M.Doran (Addison-Wensley, 2nd ed.) — A very interesting and complete book for beginners/intermediate, now off-print and free.
  • C Unleashed by Richard Heathfield and others contributors in c.l.c (Sams) — An interesting book about advanced ISO-C. Full of tricks and good practices.

Resources

Optimization Techniques

C99

Support

History

Miscellaneous

Template:Major programming languages small