C syntax

The syntax of the C programming language is the set of rules governing writing of software in the language. It is designed to allow for programs that are extremely terse, have a close relationship with the resulting object code, and yet provide relatively high-level data abstraction. C was the first widely successful high-level language for portable operating-system development.
C syntax makes use of the maximal munch principle.

Data structures

Primitive data types

The C language represents numbers in three forms: integral, real and complex. This distinction reflects similar distinctions in the instruction set architecture of most central processing units. Integral data types store numbers in the set of integers, while real and complex numbers represent numbers in the set of real numbers in floating point form.
All C integer types have and variants. If or is not specified explicitly, in most circumstances is assumed. However, for historic reasons plain is a type distinct from both and. It may be a signed type or an unsigned type, depending on the compiler and the character set. Also, bit field types specified as plain may be signed or unsigned, depending on the compiler.

Integer types

C's integer types come in different fixed sizes, capable of representing various ranges of numbers. The type occupies exactly one byte, which is typically 8 bits wide. Most integer types have both signed and unsigned varieties, designated by the and keywords. Signed integer types may use a two's complement, ones' complement, or sign-and-magnitude representation. In many cases, there are multiple equivalent ways to designate the type; for example, and are synonymous.
The representation of some types may include unused "padding" bits, which occupy storage but are not included in the width. The following table provides a complete list of the standard integer types and their minimum allowed widths.
Shortest form of specifierMinimum width

The type is distinct from both and, but is guaranteed to have the same representation as one of them. The and types are standardized since 1999, and may not be supported by older C compilers. Type is usually accessed via the typedef name defined by the standard header stdbool.h.
In general, the widths and representation scheme implemented for any given platform are chosen based on the machine architecture, with some consideration given to the ease of importing source code developed for other platforms. The width of the type varies especially widely among C implementations; it often corresponds to the most "natural" word size for the specific platform. The standard header limits.h defines macros for the minimum and maximum representable values of the standard integer types as implemented on any specific platform.
In addition to the standard integer types, there may be other "extended" integer types, which can be used for s in standard headers. For more precise specification of width, programmers can and should use s from the standard header stdint.h.
Integer constants may be specified in source code in several ways. Numeric values can be specified as decimal, octal with zero as a prefix, or hexadecimal with 0x as a prefix. A character in single quotes, called a "character constant," represents the value of that character in the execution character set, with type. Except for character constants, the type of an integer constant is determined by the width required to represent the specified value, but is always at least as wide as. This can be overridden by appending an explicit length and/or signedness modifier; for example, has type. There are no negative integer constants, but the same effect can often be obtained by using a unary negation operator "-".

Enumerated type

The enumerated type in C, specified with the keyword, and often just called an "enum", is a type designed to represent values across a series of named constants. Each of the enumerated constants has type. Each type itself is compatible with or a signed or unsigned integer type, but each implementation defines its own rules for choosing a type.
Some compilers warn if an object with enumerated type is assigned a value that is not one of its constants. However, such an object can be assigned any values in the range of their compatible type, and constants can be used anywhere an integer is expected. For this reason, values are often used in place of preprocessor directives to create named constants. Such constants are generally safer to use than macros, since they reside within a specific identifier namespace.
An enumerated type is declared with the specifier and an optional name for the enum, followed by a list of one or more constants contained within curly braces and separated by commas, and an optional list of variable names. Subsequent references to a specific enumerated type use the keyword and the name of the enum. By default, the first constant in an enumeration is assigned the value zero, and each subsequent value is incremented by one over the previous constant. Specific values may also be assigned to constants in the declaration, and any subsequent constants without specific values will be given incremented values from that point onward.
For example, consider the following declaration:
enum colors paint_color;
This declares the type; the constants , , , and ; and the variable. The constants may be used outside of the context of the enum, and values other than the constants may be assigned to, or any other variable of type.

Floating point types

The floating-point form is used to represent numbers with a fractional component. They do not, however, represent most rational numbers exactly; they are instead a close approximation. There are three types of real values, denoted by their specifiers: single precision, double precision, and double extended precision. Each of these may represent values in a different form, often one of the IEEE floating-point formats.
Floating-point constants may be written in decimal notation, e.g.. Decimal scientific notation may be used by adding or followed by a decimal exponent, also known as E notation, e.g. . Either a decimal point or an exponent is required. Hexadecimal floating-point constants follow similar rules, except that they must be prefixed by and use or to specify a binary exponent, e.g. . Both decimal and hexadecimal floating-point constants may be suffixed by or to indicate a constant of type, by or to indicate type, or left unsuffixed for a constant.
The standard header file float.h| defines the minimum and maximum values of the implementation's floating-point types,, and. It also defines other limits that are relevant to the processing of floating-point numbers.

Storage class specifiers

Every object has a storage class. This specifies most basically the storage duration, which may be static, automatic, or dynamic, together with other features.
SpecifiersLifetimeScopeDefault initializer
Block BlockUninitialized
Block BlockUninitialized
ProgramBlock or compilation unitZero
ProgramGlobal Zero
1Dynamic Uninitialized

Variables declared within a block by default have automatic storage, as do those explicitly declared with the Automatic variable| or Register | storage class specifiers. The and specifiers may only be used within functions and function argument declarations; as such, the specifier is always redundant. Objects declared outside of all blocks and those explicitly declared with the Static variable| storage class specifier have static storage duration. Static variables are initialized to zero by default by the compiler.
Objects with automatic storage are local to the block in which they were declared and are discarded when the block is exited. Additionally, objects declared with the storage class may be given higher priority by the compiler for access to registers; although the compiler may choose not to actually store any of them in a register. Objects with this storage class may not be used with the address-of unary operator. Objects with static storage persist for the program's entire duration. In this way, the same object can be accessed by a function across multiple calls. Objects with allocated storage duration are created and destroyed explicitly with malloc|,, and related functions.
The External variable| storage class specifier indicates that the storage for an object has been defined elsewhere. When used inside a block, it indicates that the storage has been defined by a declaration outside of that block. When used outside of all blocks, it indicates that the storage has been defined outside of the compilation unit. The storage class specifier is redundant when used on a function declaration. It indicates that the declared function has been defined outside of the compilation unit.
Note that storage specifiers apply only to functions and objects; other things such as type and enum declarations are private to the compilation unit in which they appear. Types, on the other hand, have qualifiers.

Type qualifiers

Types can be qualified to indicate special properties of their data. The type qualifier const indicates that a value does not change once it has been initialized. Attempting to modify a const qualified value yields undefined behavior, so some C compilers store them in rodata or in read-only memory. The type qualifier volatile indicates to an optimizing compiler that it may not remove apparently redundant reads or writes, as the value may change even if it was not modified by any expression or statement, or multiple writes may be necessary, such as for memory-mapped I/O.

Incomplete types

An incomplete type is a [|structure or union] type whose members have not yet been specified, an [|array type] whose dimension has not yet been specified, or the type. Such a type may not be instantiated, nor may its members be accessed ; however, the derived pointer type may be used.
They are often used with pointers, either as forward or external declarations. For instance, code could declare an incomplete type like this:

struct thing *pt;

This declares as a pointer to and the incomplete type. Pointers to data always have the same byte-width regardless of what they point to, so this statement is valid by itself. The incomplete type can be completed later in the same scope by redeclaring it:

struct thing ; /* thing struct type is now completed */

Incomplete types are used to implement recursive structures; the body of the type declaration may be deferred to later in the translation unit:

typedef struct Bert Bert;
typedef struct Wilma Wilma;
struct Bert ;
struct Wilma ;

Incomplete types are also used for data hiding; the incomplete type is defined in a header file, and the body only within the relevant source file.


In declarations the asterisk modifier specifies a pointer type. For example, where the specifier would refer to the integer type, the specifier refers to the type "pointer to integer". Pointer values associate two pieces of information: a memory address and a data type. The following line of code declares a pointer-to-integer variable called ptr:
int *ptr;


When a non-static pointer is declared, it has an unspecified value associated with it. The address associated with such a pointer must be changed by assignment prior to using it. In the following example, ptr is set so that it points to the data associated with the variable a:

int a = 0;
int *ptr = &a;

In order to accomplish this, the "address-of" operator is used. It produces the memory location of the data object that follows.


The pointed-to data can be accessed through a pointer value. In the following example, the integer variable b is set to the value of integer variable a, which is 10:

int a=10;
int *p;
p = &a;
int b = *p;

In order to accomplish that task, the unary dereference operator, denoted by an asterisk, is used. It returns the data to which its operand—which must be of pointer type—points. Thus, the expression *p denotes the same value as a. Dereferencing a null pointer is illegal.


Array definition

Arrays are used in C to represent structures of consecutive elements of the same type. The definition of a array has the following syntax:
int array;
which defines an array named array to hold 100 values of the primitive type. If declared within a function, the array dimension may also be a non-constant expression, in which case memory for the specified number of elements will be allocated. In most contexts in later use, a mention of the variable array is converted to a pointer to the first item in the array. The sizeof| operator is an exception: yields the size of the entire array. Another exception is the & operator, which yields a pointer to the entire array, for example
int = &array;

Accessing elements

The primary facility for accessing the values of the elements of an array is the array subscript operator. To access the i-indexed element of array, the syntax would be, which refers to the value stored in that array element.
Array subscript numbering begins at 0. The largest allowed array subscript is therefore equal to the number of elements in the array minus 1. To illustrate this, consider an array a declared as having 10 elements; the first element would be and the last element would be.
C provides no facility for automatic bounds checking for array usage. Though logically the last subscript in an array of 10 elements would be 9, subscripts 10, 11, and so forth could accidentally be specified, with undefined results.
Due to arrays and pointers being interchangeable, the addresses of each of the array elements can be expressed in equivalent pointer arithmetic. The following table illustrates both methods for the existing array:
Array subscript
Dereferenced pointer

Since the expression is semantically equivalent to, which in turn is equivalent to ; the expression can also be written as, although this form is rarely used.

Variable-length arrays

standardised variable-length arrays within block scope. Such array variables are allocated based on the value of an integer value at runtime upon entry to a block, and are deallocated at the end of the block. As of C11 this feature is no longer required to be implemented by the compiler.

int n =...;
int a;
a = 10;

This syntax produces an array whose size is fixed until the end of the block.

Dynamic arrays

Arrays that can be resized dynamically can be produced with the help of the C standard library. The function provides a simple method for allocating memory. It takes one parameter: the amount of memory to allocate in bytes. Upon successful allocation, returns a generic pointer value, pointing to the beginning of the allocated space. The pointer value returned is converted to an appropriate type implicitly by assignment. If the allocation could not be completed, returns a null pointer. The following segment is therefore similar in function to the above desired declaration:

  1. include /* declares malloc */
int *a = malloc;
a = 10;

The result is a "pointer to " variable that points to the first of n contiguous objects; due to array–pointer equivalence this can be used in place of an actual array name, as shown in the last line. The advantage in using this dynamic allocation is that the amount of memory that is allocated to it can be limited to what is actually needed at run time, and this can be changed as needed.
When the dynamically-allocated memory is no longer needed, it should be released back to the run-time system. This is done with a call to the function. It takes a single parameter: a pointer to previously allocated memory. This is the value that was returned by a previous call to.
As a security measure, some programmers then set the pointer variable to :

a = NULL;

This ensures that further attempts to dereference the pointer will crash the program. If this is not done, the variable becomes a dangling pointer which can lead to a use-after-free bug. However, if the pointer is a local variable, setting it to does not prevent the program from using other copies of the pointer. Local use-after-free bugs are usually easy for static analyzers to recognize. Therefore, this approach is less useful for local pointers and it is more often used with pointers stored in long-living structs. In general though, setting pointers to is good practice as it allows a programmer is -check pointers prior to dereferencing, thus helping prevent crashes.
Recalling the array example, one could also create a fixed-size array through dynamic allocation:

int = malloc;

...Which yields a pointer-to-array.
Accessing the pointer-to-array can be done in two ways:


Iterating can also be done in two ways:


The benefit to using the second example is that the numeric limit of the first example isn't required, which means that the pointer-to-array could be of any size and the second example can execute without any modifications.

Multidimensional arrays

In addition, C supports arrays of multiple dimensions, which are stored in row-major order. Technically, C multidimensional arrays are just one-dimensional arrays whose elements are arrays. The syntax for declaring multidimensional arrays is as follows:
int array2d;
where ROWS and COLUMNS are constants. This defines a two-dimensional array. Reading the subscripts from left to right, array2d is an array of length ROWS, each element of which is an array of COLUMNS integers.
To access an integer element in this multidimensional array, one would use
Again, reading from left to right, this accesses the 5th row, and the 4th element in that row. The expression is an array, which we are then subscripting with to access the fourth integer.
ElementFirstSecond row, second columnith row, jth column
Array subscript
Dereferenced pointer

Higher-dimensional arrays can be declared in a similar manner.
A multidimensional array should not be confused with an array of references to arrays. The former is always rectangular, and occupies a contiguous region of memory. The latter is a one-dimensional array of pointers, each of which may point to the first element of a subarray in a different place in memory, and the sub-arrays do not have to be the same size. The latter can be created by multiple uses of.


In C, string literals are surrounded by double quotes, e.g. and are compiled to an array of the specified values with an additional null terminating character code to mark the end of the string.
String literals may not contain embedded newlines; this proscription somewhat simplifies parsing of the language. To include a newline in a string, the [|backslash escape] may be used, as [|below].
There are several standard library functions for operating with string data organized as array of using this null-terminated format; see below.
C's string-literal syntax has been very influential, and has made its way into many other languages, such as C++, Objective-C, Perl, Python, PHP, Java, Javascript, C#, Ruby. Nowadays, almost all new languages adopt or build upon C-style string syntax. Languages that lack this syntax tend to precede C.

Backslash escapes

If you wish to include a double quote inside the string, that can be done by escaping it with a backslash, for example,. To insert a literal backslash, one must double it, e.g..
Backslashes may be used to enter control characters, etc., into a string:
Literal backslash
Double quote
Single quote
Carriage return
Horizontal tab
Form feed
Vertical tab
Question mark
Percentage mark, printf format strings only
\OOOCharacter with octal value OOO
\xHHCharacter with hexadecimal value HH

The use of other backslash escapes is not defined by the C standard, although compiler vendors often provide additional escape codes as language extensions.

String literal concatenation

C has string literal concatenation, meaning that adjacent string literals are concatenated at compile time; this allows long strings to be split over multiple lines, and also allows string literals resulting from C preprocessor defines and macros to be appended to strings at compile time:


will expand to


which is syntactically equivalent to


Character constants

Individual character constants are single-quoted, e.g., and have type . The difference is that represents a null-terminated array of two characters, 'A' and '\0', whereas directly represents the character value. The same backslash-escapes are supported as for strings, except that can validly be used as a character without being escaped, whereas must now be escaped.
A character constant cannot be empty, although a string may be. Multi-character constants are valid, although rarely useful — they let one store several characters in an integer. Since the order in which the characters are packed into an is not specified, portable use of multi-character constants is difficult.
Nevertheless, in situations limited to a specific platform and the compiler implementation, multicharacter constants do find their use in specifying signatures. One common use case is the OSType, where the combination of Classic Mac OS compilers and its inherent big-endianness means that bytes in the integer appear in the exact order of characters defined in the literal. The definition by popular "implementations" are in fact consistent: in GCC, Clang, and Visual C++, yields 0x31323334 under ASCII.

Wide character strings

Since type is 1 byte wide, a single value typically can represent at most 255 distinct character codes, not nearly enough for all the characters in use worldwide. To provide better support for international characters, the first C standard introduced wide characters and wide character strings, which are written as
Wide characters are most commonly either 2 bytes or 4 bytes, but Standard C does not specify the width for, leaving the choice to the implementor. Microsoft Windows generally uses UTF-16, thus the above string would be 26 bytes long for a Microsoft compiler; the Unix world prefers UTF-32, thus compilers such as GCC would generate a 52-byte string. A 2-byte wide suffers the same limitation as, in that certain characters cannot be represented in a single ; but must be represented using surrogate pairs.
The original C standard specified only minimal functions for operating with wide character strings; in 1995 the standard was modified to include much more extensive support, comparable to that for strings. The relevant functions are mostly named after their equivalents, with the addition of a "w" or the replacement of "str" with "wcs"; they are specified in, with containing wide-character classification and mapping functions.
The now generally recommended method of supporting international characters is through UTF-8, which is stored in arrays, and can be written directly in the source code if using a UTF-8 editor, because UTF-8 is a direct ASCII extension.

Variable width strings

A common alternative to is to use a variable-width encoding, whereby a logical character may extend over multiple positions of the string. Variable-width strings may be encoded into literals verbatim, at the risk of confusing the compiler, or using numerical backslash escapes. The UTF-8 encoding was specifically designed for compatibility with the standard library string functions; supporting features of the encoding include a lack of embedded nulls, no valid interpretations for subsequences, and trivial resynchronisation. Encodings lacking these features are likely to prove incompatible with the standard library functions; encoding-aware string functions are often used in such cases.

Library functions

, both constant and variable, can be manipulated without using the standard library. However, the library contains many useful functions for working with null-terminated strings.

Structures and unions


Structures and unions in C are defined as data containers consisting of a sequence of named members of various types. They are similar to records in other programming languages. The members of a structure are stored in consecutive locations in memory, although the compiler is allowed to insert padding between or after members for efficiency or as padding required for proper alignment by the target architecture. The size of a structure is equal to the sum of the sizes of its members, plus the size of the padding.


Unions in C are related to structures and are defined as objects that may hold objects of different types and sizes. They are analogous to variant records in other programming languages. Unlike structures, the components of a union all refer to the same location in memory. In this way, a union can be used at various times to hold different types of objects, without the need to create a separate object for each new type. The size of a union is equal to the size of its largest component type.


Structures are declared with the keyword and unions are declared with the keyword. The specifier keyword is followed by an optional identifier name, which is used to identify the form of the structure or union. The identifier is followed by the declaration of the structure or union's body: a list of member declarations, contained within curly braces, with each declaration terminated by a semicolon. Finally, the declaration concludes with an optional list of identifier names, which are declared as instances of the structure or union.
For example, the following statement declares a structure named that contains three members; it will also declare an instance of the structure known as :

struct s tee;

And the following statement will declare a similar union named and an instance of it named :

union u n;

Members of structures and unions cannot have an incomplete or function type. Thus members cannot be an instance of the structure or union being declared but can be pointers to the type being declared.
Once a structure or union body has been declared and given a name, it can be considered a new data type using the specifier or, as appropriate, and the name. For example, the following statement, given the above structure declaration, declares a new instance of the structure named :
struct s r;
It is also common to use the typedef specifier to eliminate the need for the or keyword in later references to the structure. The first identifier after the body of the structure is taken as the new name for the structure type. For example, the following statement will declare a new type known as s_type that will contain some structure:
typedef struct s_type;
Future statements can then use the specifier s_type to refer to the structure.

Accessing members

Members are accessed using the name of the instance of a structure or union, a period, and the name of the member. For example, given the declaration of tee from above, the member known as y can be accessed using the following syntax:
Structures are commonly accessed through pointers. Consider the following example that defines a pointer to tee, known as ptr_to_tee:
struct s *ptr_to_tee = &tee;
Member y of tee can then be accessed by dereferencing ptr_to_tee and using the result as the left operand:
Which is identical to the simpler above as long as ptr_to_tee points to tee. Due to operator precedence, the shorter *ptr_to_tee.y is incorrect for this purpose, instead being parsed as * and thus the parentheses are necessary. Because this operation is common, C provides an abbreviated syntax for accessing a member directly from a pointer. With this syntax, the name of the instance is replaced with the name of the pointer and the period is replaced with the character sequence. Thus, the following method of accessing y is identical to the previous two:
Members of unions are accessed in the same way.
This can be chained; for example, in a linked list, one may refer to n->next->next for the second following node.


Assigning values to individual members of structures and unions is syntactically identical to assigning values to any other object. The only difference is that the lvalue of the assignment is the name of the member, as accessed by the syntax mentioned above.
A structure can also be assigned as a unit to another structure of the same type. Structures may also be used as function parameter and return types.
For example, the following statement assigns the value of 74 to the member named x in the structure tee, from above:
tee.x = 74;
And the same assignment, using ptr_to_tee in place of tee, would look like:
ptr_to_tee->x = 74;
Assignment with members of unions is identical.

Other operations

According to the C standard, the only legal operations that can be performed on a structure are copying it, assigning to it as a unit, taking its address with the address-of unary operator, and accessing its members. Unions have the same restrictions. One of the operations implicitly forbidden is comparison: structures and unions cannot be compared using C's standard comparison facilities.

Bit fields

C also provides a special type of structure member known as a bit field, which is an integer with an explicitly specified number of bits. A bit field is declared as a structure member of type,,, or, following the member name by a colon and the number of bits it should occupy. The total number of bits in a single bit field must not exceed the total number of bits in its declared type.
As a special exception to the usual C syntax rules, it is implementation-defined whether a bit field declared as type, without specifying or, is signed or unsigned. Thus, it is recommended to explicitly specify or on all structure members for portability.
Unnamed fields consisting of just a colon followed by a number of bits are also allowed; these indicate padding. Specifying a width of zero for an unnamed field is used to force alignment to a new word.
The members of bit fields do not have addresses, and as such cannot be used with the address-of unary operator. The operator may not be applied to bit fields.
The following declaration declares a new structure type known as and an instance of it known as. Comments provide a description of each of the members:

struct f g;


Default initialization depends on the storage class specifier, described above.
Because of the language's grammar, a scalar initializer may be enclosed in any number of curly brace pairs. Most compilers issue a warning if there is more than one such pair, though.
int x = 12;
int y = ; //Legal, no warning
int z = ; //Legal, expect a warning

Structures, unions and arrays can be initialized in their declarations using an initializer list. Unless designators are used, the components of an initializer correspond with the elements in the order they are defined and stored, thus all preceding values must be provided before any particular element's value. Any unspecified elements are set to zero. Mentioning too many initialization values yields an error.
The following statement will initialize a new instance of the structure s known as pi:
struct s ;
struct s pi = ;

Designated initializers

Designated initializers allow members to be initialized by name, in any order, and without explicitly providing the preceding values. The following initialization is equivalent to the previous one:
struct s pi = ;
Using a designator in an initializer moves the initialization "cursor". In the example below, if MAX is greater than 10, there will be some zero-valued elements in the middle of a; if it is less than 10, some of the values provided by the first five initializers will be overridden by the second five :
int a = ;
In C89, a union was initialized with a single value applied to its first member. That is, the union u defined above could only have its int x member initialized:
union u value = ;
Using a designated initializer, the member to be initialized does not have to be the first member:
union u value = ;
If an array has unknown size, the number of initializers determines the size of the array and its type becomes complete:

int x = ;

Compound designators can be used to provide explicit initialization when unadorned initializer lists
might be misunderstood. In the example below, w is declared as an array of structures, each structure consisting of a member a and a member b. The initializer sets the size of w to 2 and sets the values of the first element of each a:
struct w = ;
This is equivalent to:struct w =

There is no way to specify repetition of an initializer in standard C.

Compound literals

It is possible to borrow the initialization methodology to generate compound structure and array literals:

// pointer created from array literal.
int *ptr = ;
// pointer to array.
float = &;
struct s pi = ;

Compound literals are often combined with designated initializers to make the declaration more readable:
pi = ;


Control structures

C is a free-form language.
Bracing style varies from programmer to programmer and can be the subject of debate. See Indent style for more details.

Compound statements

In the items in this section, any can be replaced with a compound statement. Compound statements have the form:

and are used as the body of a function or anywhere that a single statement is expected. The declaration-list declares variables to be used in that scope, and the statement-list are the actions to be performed. Brackets define their own scope, and variables defined inside those brackets will be automatically
deallocated at the closing bracket. Declarations and statements can be freely intermixed within a compound statement.

Selection statements

C has two types of selection statements: the statement and the statement.
The statement is in the form:



In the statement, if the in parentheses is nonzero, control passes to. If the clause is present and the is zero, control will pass to. The part is optional and, if absent, a false will simply result in skipping over the. An always matches the nearest previous unmatched ; braces may be used to override this when necessary, or for clarity.
The statement causes control to be transferred to one of several statements depending on the value of an expression, which must have integral type. The substatement controlled by a switch is typically compound. Any statement within the substatement may be labeled with one or more labels, which consist of the keyword followed by a constant expression and then a colon. The syntax is as follows:


No two of the case constants associated with the same switch may have the same value. There may be at most one label associated with a switch. If none of the case labels are equal to the expression in the parentheses following, control passes to the label or, if there is no label, execution resumes just beyond the entire construct.
Switches may be nested; a or label is associated with the innermost that contains it. Switch statements can "fall through", that is, when one case section has completed its execution, statements will continue to be executed downward until a statement is encountered. Fall-through is useful in some circumstances, but is usually not desired.
In the preceding example, if is reached, the statements are executed and nothing more inside the braces. However, if is reached, both and are executed since there is no to separate the two case statements.
It is possible, although unusual, to insert the labels into the sub-blocks of other control structures. Examples of this include Duff's device and Simon Tatham's implementation of coroutines in Putty.

Iteration statements

C has three forms of iteration statement:


while ;


In the while loop| and statements, the sub-statement is executed repeatedly so long as the value of the remains non-zero. With, the test, including all side effects from, occurs before each iteration ; with, the test occurs after each iteration. Thus, a statement always executes its sub-statement at least once, whereas may not execute the sub-statement at all.
The statement:


is equivalent to:


except for the behaviour of a statement. If is blank, it would have to be replaced with a.
Any of the three expressions in the loop may be omitted. A missing second expression makes the test always non-zero, creating a potentially infinite loop.
Since C99, the first expression may take the form of a declaration, typically including an initializer, such as:


The declaration's scope is limited to the extent of the loop.

Jump statements

Jump statements transfer control unconditionally. There are four types of jump statements in C: GOTO|,,, and return statement|.
The statement looks like this:

goto ;

The identifier must be a label located in the current function. Control transfers to the labeled statement.
A statement may appear only within an iteration statement and causes control to pass to the loop-continuation portion of the innermost enclosing iteration statement. That is, within each of the statements

while ;

a not contained within a nested iteration statement is the same as.
The statement is used to end a loop, loop, loop, or statement. Control passes to the statement following the terminated statement.
A function returns to its caller by the statement. When is followed by an expression, the value is returned to the caller as the value of the function. Encountering the end of the function is equivalent to a with no expression. In that case, if the function is declared as returning a value and the caller tries to use the returned value, the result is undefined.

Storing the address of a label

extends the C language with a unary operator that returns the address of a label. This address can be stored in a variable type and may be used later in a instruction. For example, the following prints in an infinite loop:

void *ptr = &&J1;
J1: printf;
goto *ptr;

This feature can be used to implement a jump table.



A C function definition consists of a return type, a unique name, a list of parameters in parentheses, and various statements:


A function with non- return type should include at least one statement. The parameters are given by the, a comma-separated list of parameter declarations, each item in the list being a data type followed by an identifier:.
If there are no parameters, the may be left empty or optionally be specified with the single word.
It is possible to define a function as taking a variable number of parameters by providing the keyword as the last parameter instead of a data type and variable identifier. A commonly used function that does this is the standard library function, which has the declaration:

int printf ;

Manipulation of these parameters can be done by using the routines in the standard library header stdarg.h|.

Function Pointers

A pointer to a function can be declared as follows:


The following program shows use of a function pointer for selecting between addition and subtraction:

  1. include
int ;
int add
int subtract
int main

Global structure

After preprocessing, at the highest level a C program consists of a sequence of declarations at file scope. These may be partitioned into several separate source files, which may be compiled separately; the resulting object modules are then linked along with implementation-provided run-time support modules to produce an executable image.
The declarations introduce functions, variables and types. C functions are akin to the subroutines of Fortran or the procedures of Pascal.
A definition is a special type of declaration. A variable definition sets aside storage and possibly initializes it, a function definition provides its body.
An implementation of C providing all of the standard library functions is called a hosted implementation. Programs written for hosted implementations are required to define a special function called Entry point|, which is the first function called when a program begins executing.
Hosted implementations start program execution by invoking the function, which must be defined following one of these prototypes:

int main
int main
int main
int main

The first two definitions are equivalent. It is probably up to individual preference which one is used. The return value of serves as termination status returned to the host environment.
The C standard defines return values and as indicating success and as indicating failure.. Other return values have implementation-defined meanings; for example, under Linux a program killed by a signal yields a return code of the numerical value of the signal plus 128.
A minimal correct C program consists of an empty routine, taking no arguments and doing nothing:

int main

Because no return statement is present, main returns 0 on exit.
The function will usually call other functions to help it perform its job.
Some implementations are not hosted, usually because they are not intended to be used with an operating system. Such implementations are called free-standing in the C standard. A free-standing implementation is free to specify how it handles program startup; in particular it need not require a program to define a function.
Functions may be written by the programmer or provided by existing libraries. Interfaces for the latter are usually declared by including header files—with the preprocessing directive—and the library objects are linked into the final executable image. Certain library functions, such as printf|, are defined by the C standard; these are referred to as the standard library functions.
A function may return a value to caller. The function mentioned above returns how many characters were printed, but this value is often ignored.

Argument passing

In C, arguments are passed to functions by value while other languages may pass variables by reference.
This means that the receiving function gets copies of the values and has no direct way of altering the original variables.
For a function to alter a variable passed from another function, the caller must pass its address, which can then be dereferenced in the receiving function. See Pointers for more information.

void incInt
int main

The function scanf works the same way:

int x;

In order to pass an editable pointer to a function you have to pass a pointer to that pointer: its address.

  1. include
  2. include
void allocate_array
int main

The parameter is a pointer to a pointer to an, which is the address of the pointer defined in the main function in this case.

Array parameters

Function parameters of array type may at first glance appear to be an exception to C's pass-by-value rule. The following program will print 2, not 1:

  1. include
void setArray
int main

However, there is a different reason for this behavior. In fact, a function parameter declared with an array type is treated like one declared to be a pointer. That is, the preceding declaration of is equivalent to the following:

void setArray

At the same time, C rules for the use of arrays in expressions cause the value of in the call to to be converted to a pointer to the first element of array. Thus, in fact this is still an example of pass-by-value, with the caveat that it is the address of the first element of the array being passed by value, not the contents of the array.


Reserved keywords

The following words are reserved, and may not be used as identifiers:
Implementations may reserve other keywords, such as, although implementations typically provide non-standard keywords that begin with one or two underscores.

Case sensitivity

C identifiers are case sensitive. Some linkers may map external identifiers to a single case, although this is uncommon in most modern linkers.


Text starting with the token is treated as a comment and ignored. The comment ends at the next ; it can occur within expressions, and can span multiple lines. Accidental omission of the comment terminator is problematic in that the next comment's properly constructed comment terminator will be used to terminate the initial comment, and all code in between the comments will be considered as a comment. C-style comments do not nest; that is, accidentally placing a comment within a comment has unintended results:

This line will be ignored.
A compiler warning may be produced here. These lines will also be ignored.
The comment opening token above did not start a new comment,
and the comment closing token below will close the comment begun on line 1.
  • /
This line and the line below it will not be ignored. Both will likely produce compile errors.
  • /

C++ style line comments start with and extend to the end of the line. This style of comment originated in BCPL and became valid C syntax in C99; it is not available in the original K&R C nor in ANSI C:

// this line will be ignored by the compiler
/* these lines
will be ignored
by the compiler */
x = *p/*q; /* this comment starts after the 'p' */

Command-line arguments

The parameters given on a command line are passed to a C program with two predefined variables - the count of the command-line arguments in and the individual arguments as character strings in the pointer array. So the command:
myFilt p1 p2 p3
results in something like:
While individual strings are arrays of contiguous characters, there is no guarantee that the strings are stored as a contiguous group.
The name of the program,, may be useful when printing diagnostic messages or for making one binary serve multiple purposes. The individual values of the parameters may be accessed with,, and, as shown in the following program:

  1. include
int main

Evaluation order

In any reasonably complex expression, there arises a choice as to the order in which to evaluate the parts of the expression: may be evaluated in the order,,,, or in the order,,,. Formally, a conforming C compiler may evaluate expressions in any order between sequence points. Sequence points are defined by:
  • Statement ends at semicolons.
  • The sequencing operator: a comma. However, commas that delimit function arguments are not sequence points.
  • The short-circuit operators: logical and and logical or.
  • The : This operator evaluates its first sub-expression first, and then its second or third based on the value of the first.
  • Entry to and exit from a function call.
Expressions before a sequence point are always evaluated before those after a sequence point. In the case of short-circuit evaluation, the second expression may not be evaluated depending on the result of the first expression. For example, in the expression, if the first argument evaluates to nonzero, the result of the entire expression cannot be anything else than true, so is not evaluated. Similarly, in the expression, if the first argument evaluates to zero, the result of the entire expression cannot be anything else than false, so is not evaluated.
The arguments to a function call may be evaluated in any order, as long as they are all evaluated by the time the function is entered. The following expression, for example, has undefined behavior:


Undefined behavior

An aspect of the C standard is that the behavior of certain code is said to be "undefined". In practice, this means that the program produced from this code can do anything, from working as the programmer intended, to crashing every time it is run.
For example, the following code produces undefined behavior, because the variable b is modified more than once with no intervening sequence point:

  1. include
int main

Because there is no sequence point between the modifications of b in "b++ + b++", it is possible to perform the evaluation steps in more than one order, resulting in an ambiguous statement. This can be fixed by rewriting the code to insert a sequence point in order to enforce an unambiguous behavior, for example:

a = b++;
a += b++;