C- Programming

Saturday, October 2, 2010

C (pronounced /ˈsiː/ see) is a general-purpose computer programming language developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system.[3]
Although C was designed for implementing system software,[4] it is also widely used for developing portable application software.
C is one of the most popular programming languages of all time[5][6] and there are very few computer architectures for which a C compiler does not exist. C has greatly influenced many other popular programming languages, most notably C++, which began as an extension to C.
Design
C is an imperative (procedural) systems implementation language. It was designed to be compiled using a relatively straightforward compiler, to provide low-level access to memory, to provide language constructs that map efficiently to machine instructions, and to require minimal run-time support. C was therefore useful for many applications that had formerly been coded in assembly language.
Despite its low-level capabilities, the language was designed to encourage cross-platform programming. A standards-compliant and portably written C program can be compiled for a very wide variety of computer platforms and operating systems with little or no change to its source code. The language has become available on a very wide range of platforms, from embedded microcontrollers to supercomputers.
[edit]
Minimalism
C's design is tied to its intended use as a portable systems implementation language. It provides simple, direct access to any addressable object (for example, memory-mapped device control registers), and its source-code expressions can be translated in a straightforward manner to primitive machine operations in the executable code. Some early C compilers were comfortably implemented (as a few distinct passes communicating via intermediate files) on PDP-11 processors having only 16 address bits; however, C99 assumes a 512 KB minimum compilation platform. Target platforms for C programs range from 8-bit microcontrollers to supercomputers.
[edit]
Characteristics
Like most imperative languages in the ALGOL tradition, C has facilities for structured programming and allows lexical variable scope and recursion, while a static type system prevents many unintended operations. In C, all executable code is contained within functions. Function parameters are always passed by value. Pass-by-reference is simulated in C by explicitly passing pointer values. Heterogeneous aggregate data types (struct) allow related data elements to be combined and manipulated as a unit. C program source text is free-format, using the semicolon as a statement terminator.
C also exhibits the following more specific characteristics:
Variables may be hidden in nested blocks
Partially weak typing; for instance, characters can be used as integers
Low-level access to computer memory by converting machine addresses to typed pointers
Function and data pointers supporting ad hoc run-time polymorphism
array indexing as a secondary notion, defined in terms of pointer arithmetic
A preprocessor for macro definition, source code file inclusion, and conditional compilation
Complex functionality such as I/O, string manipulation, and mathematical functions consistently delegated to library routines
A relatively small set of reserved keywords
A large number of compound operators, such as +=, -=, *=, ++ etc.

C's lexical structure resembles B more than ALGOL. For example:
{ ... } rather than begin ... end
= is used for assignment (copying), like Fortran, rather than ALGOL's :=
== is used to test for equality (rather than .EQ. in Fortran, or = in BASIC and ALGOL)
Logical "and" and "or" are represented with && and ||, which don't evaluate the right operand if the result can be determined from the left alone (short-circuit evaluation), and are semantically distinct from the bit-wise operators & and |
[edit]
Absent features
The relatively low-level nature of the language affords the programmer close control over what the computer does, and allows special tailoring and aggressive optimization for a particular platform. This allows the code to run efficiently on very limited hardware, such as embedded systems, and keeps the language definition small enough to allow the programmer to understand the entire language, but at the cost of some features not being included that are available in other languages:
No nested function definitions
No direct assignment of arrays or strings (copying can be done via standard functions; assignment of objects having struct or union type is supported)
No automatic garbage collection
No requirement for bounds checking of arrays
No operations on whole arrays at the language level
No syntax for ranges, such as the A..B notation used in several languages
Prior to C99, no separate Boolean type (1 (true) and 0 (false) are used instead)[7]
No formal closures or functions as parameters (only function pointers)
No generators or coroutines; intra-thread control flow consists of nested function calls, except for the use of the longjmp library function
No built-in exception handling; standard library functions signify error conditions with the global errno variable and/or special return values
Only rudimentary support for modular programming
No compile-time polymorphism in the form of function or operator overloading
Very limited support for object-oriented programming with regard to polymorphism and inheritance
Limited support for encapsulation
No native support for multithreading and networking
No standard libraries for computer graphics and several other application programming needs

A number of these features are available as extensions in some compilers, or are provided in some operating environments (e.g., POSIX), or are supplied by third-party libraries, or can be simulated by adopting certain coding disciplines.
[edit]
Undefined behavior
Many operations in C that have undefined behavior are not required to be diagnosed at compile time. In the case of C, "undefined behavior" means that the exact behavior which arises is not specified by the standard, and exactly what will happen does not have to be documented by the C implementation. A famous and humorous expression in the newsgroups comp.std.c and comp.lang.c is that the program could cause "demons to fly out of your nose".[8] Sometimes in practice what happens for an instance of undefined behavior is a bug that is hard to track down and which may corrupt the contents of memory. Sometimes a particular compiler generates reasonable and well-behaved actions that are completely different from those that would be obtained using a different C compiler. The reason some behavior has been left undefined is to allow compilers for a wide variety of instruction set architectures to generate more efficient executable code for well-defined behavior, which was deemed important for C's primary role as a systems implementation language; thus C makes it the programmer's responsibility to avoid undefined behavior, possibly using tools to find parts of a program whose behavior is undefined. Examples of undefined behavior are:
accessing outside the bounds of an array
overflowing a signed integer
reaching the end of a non-void function without finding a return statement, when the return value is used
reading the value of a variable before initializing it
These operations are all programming errors that could occur using many programming languages; C draws criticism because its standard explicitly identifies numerous cases of undefined behavior, including some where the behavior could have been made well defined, and does not specify any run-time error handling mechanism.
Invoking fflush() on a stream opened for input is an example of a different kind of undefined behavior, not necessarily a programming error but a case for which some conforming implementations may provide well-defined, useful semantics (in this example, presumably discarding input through the next new-line) as an allowed extension. Over-reliance on nonstandard extensions undermines software portability.
[edit]
History
[edit]
Early developments
The initial development of C occurred at AT&T Bell Labs between 1969 and 1973;[2] according to Ritchie, the most creative period occurred in 1972. It was named "C" because its features were derived from an earlier language called "B", which according to Ken Thompson was a stripped-down version of the BCPL programming language.

The origin of C is closely tied to the development of the Unix operating system, originally implemented in assembly language on a PDP-7 by Ritchie and Thompson, incorporating several ideas from colleagues. Eventually they decided to port the operating system to a PDP-11. B's inability to take advantage of some of the PDP-11's features, notably byte addressability, led to the development of an early version of C.

The original PDP-11 version of the Unix system was developed in assembly language. By 1973, with the addition of struct types, the C language had become powerful enough that most of the Unix kernel 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 the Burroughs B5000 written in ALGOL in 1961.)

K&R C
In 1978, Brian Kernighan and Dennis Ritchie published the first edition of The C Programming Language.[9] 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[1] covers the later ANSI C standard.

K&R introduced several language features:
standard I/O library
long int data type
unsigned int data type
compound assignment operators of the form =op (such as =-) were changed to the form op= to remove the semantic ambiguity created by such constructs as i=-10, which had been interpreted as i =- 10 instead of the possibly intended i = -10

Even after the publication of the 1989 C standard, for many years K&R C was still considered the "lowest common denominator" to which C programmers restricted themselves when maximum portability was desired, since many older compilers were still in use, and because carefully written K&R C code can be legal Standard C as well.
In early versions of C, only functions that returned a non-int value needed to be declared if used before the function definition; a function used without any previous declaration was assumed to return type int, if its value was used.

For example:
long int SomeFunction();
/* int OtherFunction(); */

/* int */ CallingFunction()
{
long int test1;
register /* int */ test2;

test1 = SomeFunction();
if (test1 > 0)
test2 = 0;
else
test2 = OtherFunction();

return test2;
}

All the above commented-out int declarations could be omitted in K&R C.

Since K&R function declarations 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 local function was called with the wrong number of arguments, or if multiple calls to an external function used different numbers or types of arguments. Separate tools such as Unix's lint utility were developed that (among other things) could check for consistency of function use across multiple source files.

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
functions returning struct or union types (rather than pointers)
assignment for struct data types
enumerated types

The large number of extensions and lack of agreement on a standard library, together with the language popularity and the fact that not even the Unix compilers precisely implemented the K&R specification, led to the necessity of standardization.
[edit]
ANSI C and ISO C
Main article: ANSI C

During the late 1970s and 1980s, versions of C were implemented for a wide variety of mainframe computers, minicomputers, and microcomputers, including the IBM PC, as its popularity began to increase significantly.

In 1983, the American National Standards Institute (ANSI) formed a committee, X3J11, to establish a standard specification of C. In 1989, the standard was ratified as ANSI X3.159-1989 "Programming Language C". This version of the language is often referred to as ANSI C, Standard C, or sometimes C89.

In 1990, the ANSI C standard (with formatting changes) was adopted by the International Organization for Standardization (ISO) as ISO/IEC 9899:1990, which is sometimes called C90. Therefore, the terms "C89" and "C90" refer to the same programming language.

ANSI, like other national standards bodies, no longer develops the C standard independently, but defers to the ISO C standard. National adoption of updates to the international standard typically occurs within a year of ISO publication.

One of the aims of the C standardization process was to produce a superset of K&R C, incorporating many of the unofficial features subsequently introduced. The standards committee also included several additional features such as function prototypes (borrowed from C++), void pointers, support for international character sets and locales, and preprocessor enhancements. The syntax for parameter declarations was also augmented to include the style used in C++, although the K&R interface continued to be permitted, for compatibility with existing source code.

C89 is supported by current C compilers, and most C code being written nowadays is based on it. Any program written only in Standard C and without any hardware-dependent assumptions will run correctly on any platform with a conforming C implementation, within its resource limits. Without such precautions, programs may compile only on a certain platform or with a particular compiler, due, for example, to the use of non-standard libraries, such as GUI libraries, or to a reliance on compiler- or platform-specific attributes such as the exact size of data types and byte endianness.

In cases where code must be compilable by either standard-conforming or K&R C-based compilers, the __STDC__ macro can be used to split the code into Standard and K&R sections to prevent using on a K&R C-based compiler features available only in Standard C.
[edit]
C99
Main article: C99

After the ANSI/ISO standardization process, the C language specification remained relatively static for some time. In 1995 Normative Amendment 1 to the 1990 C standard was published, to correct some details and to add more extensive support for international character sets. The C standard was further revised in the late 1990s, leading to the publication of ISO/IEC 9899:1999 in 1999, which is commonly referred to as "C99". It has since been amended three times by Technical Corrigenda. The international C standard is maintained by the working group ISO/IEC JTC1/SC22/WG14.

C99 introduced several new features, including inline functions, several new data types (including long long int and a complex type to represent complex numbers), variable-length arrays, support for variadic macros (macros of variable arity) and support for one-line comments beginning with //, as in BCPL or C++. Many of these had already been implemented as extensions in several C compilers.

C99 is for the most part backward compatible with C90, but is stricter in some ways; in particular, a declaration that lacks a type specifier no longer has int implicitly assumed. A standard macro __STDC_VERSION__ is defined with value 199901L to indicate that C99 support is available. GCC, Sun Studio and other C compilers now support many or all of the new features of C99.
[edit]
C1X
Main article: C1X

In 2007, work began in anticipation of another revision of the C standard, informally called "C1X". The C standards committee has adopted guidelines to limit the adoption of new features that have not been tested by existing implementations.
[edit]
Uses

C is often used for "system programming", including implementing operating systems and embedded system applications, due to a combination of desirable characteristics such as code portability and efficiency, ability to access specific hardware addresses, ability to pun types to match externally imposed data access requirements, and low runtime demand on system resources. C can also be used for website programming using CGI as a "gateway" for information between the Web application, the server, and the browser.[10] Some reasons for choosing C over interpreted languages are its speed, stability, and near-universal availability.[11]

One consequence of C's wide acceptance and efficiency is that compilers, libraries, and interpreters of other programming languages are often implemented in C. The primary implementations of Python (CPython), Perl 5, and PHP are all written in C.

Due to its thin layer of abstraction and low overhead, C allows efficient implementations of algorithms and data structures, which is useful for programs that perform a lot of computations. For example, the GNU Multi-Precision Library, the GNU Scientific Library, Mathematica and MATLAB are completely or partially written in C.

C is sometimes used as an intermediate language by implementations of other languages. This approach may be used for portability or convenience; by using C as an intermediate language, it is not necessary to develop machine-specific code generators. Some languages and compilers which have used C this way are BitC, C++, Eiffel, Gambit, GHC, Squeak, and Vala. However, C was designed as a programming language, not as a compiler target language, and is thus less than ideal for use as an intermediate language. This has led to development of C-based intermediate languages such as C--.

C has also been widely used to implement end-user applications, but much of that development has shifted to newer languages.
[edit]
Syntax
Main article: C syntax

Unlike languages such as FORTRAN 77, C source code is free-form which allows arbitrary use of whitespace to format code, rather than column-based or text-line-based restrictions. Comments may appear either between the delimiters /* and */, or (in C99) following // until the end of the line.

C source files contain 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 specify built-in types. Sections of code are enclosed in braces ({ and }, sometimes called "curly brackets") to limit the scope of declarations and to act as a single statement for control structures.

As an imperative language, C uses statements to specify actions. The most common statement is an expression statement, consisting of an expression to be evaluated, followed by a semicolon; as a side effect of the evaluation, functions may be called and variables may be assigned new values. To modify the normal sequential execution of statements, C provides several control-flow statements identified by reserved keywords. Structured programming is supported by if(-else) conditional execution and by do-while, while, and for iterative execution (looping). The for statement has separate initialization, testing, and reinitialization expressions, any or all of which can be omitted. break and continue can be used to leave the innermost enclosing loop statement or skip to its reinitialization. There is also a non-structured goto statement which branches directly to the designated label within the function. switch selects a case to be executed based on the value of an integer expression.

Expressions can use a variety of built-in operators (see below) and may contain function calls. The order in which arguments to functions and operands to most operators are evaluated is unspecified. The evaluations may even be interleaved. However, all side effects (including storage to variables) will occur before the next "sequence point"; sequence points include the end of each expression statement, and the entry to and return from each function call. Sequence points also occur during evaluation of expressions containing certain operators(&&, ||, ?: and the comma operator). This permits a high degree of object code optimization by the compiler, but requires C programmers to take more care to obtain reliable results than is needed for other programming languages.

Although mimicked by many languages because of its widespread familiarity, C's syntax has often been criticized. For example, Kernighan and Ritchie say in the Introduction 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."

Some specific problems worth noting are:
Not checking number and types of arguments when the function declaration has an empty parameter list. (This provides 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, which would need to be written (x & 1) == 0 to be properly evaluated.
The use of the = operator, used in mathematics for equality, to indicate assignment, following the precedent of Fortran and PL/I, but unlike ALGOL and its derivatives. Ritchie made this syntax design decision consciously, based primarily on the argument that assignment occurs more often than comparison.
Similarity of the assignment and equality operators (= and ==), making it easy to accidentally substitute one for the other. In many cases, each may be used in the context of the other without a compilation error (although some compilers produce warnings). For example, the conditional expression in if (a=b) is true if a is not zero after the assignment.[12]
A lack of infix operators for complex objects, particularly for string operations, making programs which rely heavily on these operations (implemented as functions instead) somewhat difficult to read.
A declaration syntax that some find unintuitive, particularly for function pointers. (Ritchie's idea was to declare identifiers in contexts resembling their use: "declaration reflects use".)
[edit]
Operators
Main article: Operators in C and C++

C supports a rich set of operators, which are symbols used within an expression to specify the manipulations to be performed while evaluating that expression. C has operators for:
arithmetic (+, -, *, /, %)
assignment (=) and augmented assignment (+=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=)
bitwise logic (~, &, |, ^)
bitwise shifts (<<, >>)
boolean logic (!, &&, ||)
conditional evaluation (? :)
equality testing (==, !=)
function argument collection (( ))
increment and decrement (++, --)
member selection (., ->)
object size (sizeof)
order relations (<, <=, >, >=)
reference and dereference (&, *, [ ])
sequencing (,)
subexpression grouping (( ))
type conversion ((typename))

C has a formal grammar,[13] specified by the C standard.
[edit]
"Hello, world" example

The "hello, world" example which appeared in the first edition of K&R has become the model for an introductory program in most programming textbooks, regardless of programming language. The program prints "hello, world" to the standard output, which is usually a terminal or screen display.

The original version was:
main()
{
printf("hello, world\n");
}

A standard-conforming "hello, world" program is:[14]
#include

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

The first line of the program contains a preprocessing directive, indicated by #include. This causes the preprocessor—the first tool to examine source code as it is compiled—to substitute the line with the entire text of the stdio.h standard header, which contains declarations for standard input and output functions such as printf. The angle brackets surrounding stdio.h indicate that stdio.h is located using a search strategy that prefers standard headers to other headers having the same name. Double quotes may also be used to include local or project-specific header files.

The next line indicates that a function named main is being defined. The main function serves a special purpose in C programs; the run-time environment calls the main function to begin program execution. The type specifier int indicates that the return value, the value that is returned to the invoker (in this case the run-time environment) as a result of evaluating the main function, is an integer. The keyword void as a parameter list indicates that the main function takes no arguments.[15]

The opening curly brace indicates the beginning of the definition of the main function.

The next line calls (diverts execution to) a function named printf, which was declared in stdio.h and is supplied from a system library. 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 string literal is an unnamed array with elements of type char, set up automatically by the compiler with a final 0-valued character to mark the end of the array (printf needs to know this). The \n is an escape sequence that C translates to a newline character, which on output signifies the end of the current line. The return value of the printf function is of type int, but it is silently discarded since it is not used. (A more careful program might test the return value to determine whether or not the printf function succeeded.) The semicolon ; terminates the statement.

The return statement terminates the execution of the main function and causes it to return the integer value 0, which is interpreted by the run-time system as an exit code indicating successful execution.

The closing curly brace indicates the end of the code for the main function.
[edit]
Data types
Main article: C variable types and declarations

C has a static weak typing type system that shares some similarities with that of other ALGOL descendants such as Pascal. There are built-in types for integers of various sizes, both signed and unsigned, floating-point numbers, characters, and enumerated types (enum). C99 added a boolean datatype. 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 type cast 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.
[edit]
Pointers

C supports the use of pointers, a very simple type of reference that records, in effect, the address or location of an object or function in memory. Pointers can be dereferenced to access data stored at the address pointed to, or to invoke a pointed-to function. Pointers can be manipulated using assignment and also pointer arithmetic. The run-time representation of a pointer value is typically a raw memory address (perhaps augmented by an offset-within-word field), but since a pointer's type includes the type of the thing pointed to, expressions including pointers can be type-checked at compile time. Pointer arithmetic is automatically scaled by the size of the pointed-to data type. (See Array-pointer interchangeability below.) 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. Many data types, such as trees, are commonly implemented as dynamically allocated struct objects linked together using pointers. Pointers to functions are useful for callbacks from event handlers.

A null pointer is a pointer that points to no valid location by having a value of 0.[16] Dereferencing a null pointer is therefore meaningless, typically resulting in a run-time error. Null pointers are useful for indicating special cases such as no next pointer in the final node of a linked list, or as an error indication from functions returning pointers. In code, null pointers are usually represented by 0 or NULL.

Void pointers (void *) point to objects of unknown type, and can therefore be used as "generic" data pointers. Since the size and type of the pointed-to object is not known, void pointers cannot be dereferenced, nor is pointer arithmetic on them allowed, although they can easily be (and in many contexts implicitly are) converted to and from any other object pointer type.

Careless use of pointers is potentially dangerous. Because they are typically unchecked, a pointer variable can be made to point to any arbitrary location, which can cause undesirable effects. Although properly-used pointers point to safe places, they can be made to point to unsafe places by using invalid pointer arithmetic; the objects they point to may be deallocated and reused (dangling pointers); they may be used without having been initialized (wild pointers); or they may be directly assigned an unsafe value using a cast, union, or through another corrupt pointer. In general, C is permissive in allowing manipulation of and conversion between pointer types, although compilers typically provide options for various levels of checking. Some other programming languages address these problems by using more restrictive reference types.
[edit]
Arrays

Array types in C are traditionally of a fixed, static size specified at compile time. (The more recent C99 standard also allows a form of variable-length arrays.) However, it is also possible to allocate a block of memory (of arbitrary size) at run-time, using the standard library's malloc function, 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. Since arrays are always accessed (in effect) via pointers, array accesses are typically not checked against the underlying array size, although the compiler may provide bounds checking as an option. Array bounds violations are therefore possible and rather common in carelessly written code, and can lead to various repercussions, including illegal memory accesses, corruption of data, buffer overruns, and run-time exceptions.

Although C supports static arrays, it is not required that array indices be validated (bounds checking). For example, one can try to write to the sixth element of an array with five elements, generally yielding undesirable results. This type of bug, called a buffer overflow or buffer overrun, is notorious for causing a number of security problems. Since bounds checking elimination technology was largely nonexistent when C was defined, bounds checking came with a severe performance penalty, particularly in numerical computation. A few years earlier, some Fortran compilers had a switch to toggle bounds checking on or off; however, this would have been much less useful for C, where array arguments are passed as simple pointers.

C does not have a special provision for declaring multidimensional arrays, but rather relies on recursion within the type system to declare arrays of arrays, which effectively accomplishes the same thing. The index values of the resulting "multidimensional array" can be thought of as increasing in row-major order.

Multidimensional arrays are commonly used in numerical algorithms (mainly from applied linear algebra) to store matrices. The structure of the C array is well suited to this particular task. However, since arrays are passed merely as pointers, the bounds of the array must be known fixed values or else explicitly passed to any subroutine that requires them, and dynamically sized arrays of arrays cannot be accessed using double indexing. (A workaround for this is to allocate the array with an additional "row vector" of pointers to the columns.)

C99 introduced "variable-length arrays" which address some, but not all, of the issues with ordinary C arrays.
See also: C string
[edit]
Array-pointer interchangeability

A distinctive (but potentially 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 object 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 bytes, but rather incremented by i multiplied by the size of an element that x points to. The size of these elements can be determined with the operator sizeof by applying it to any dereferenced element of x, as in n = sizeof *x or n = sizeof x[0].

Furthermore, in most expression contexts (a notable exception is as operand of sizeof), the name of an array is automatically converted to a pointer to the array's first element; this implies that an array is never copied as a whole when named as an argument to a function, but rather only the address of its first element is passed. Therefore, although function calls in C use pass-by-value semantics, arrays are in effect passed by reference.

The number of elements in a declared array x can be determined as sizeof x / sizeof x[0].

An interesting demonstration of the interchangeability of pointers and arrays is shown below. The four assignments are equivalent and each is valid C code.
/* x is an array OR a pointer. i is an integer. */

x[i] = 1; /* equivalent to *(x + i) */
*(x + i) = 1;
*(i + x) = 1;
i[x] = 1; /* equivalent to *(i + x) */

Note that although all four assignments are equivalent, only the first represents good coding style. The last line might be found in obfuscated C code.

Despite this apparent equivalence between array and pointer variables, there is still a distinction to be made between them. Even though the name of an array is, in most expression contexts, converted into a pointer (to its first element), this pointer does not itself occupy any storage, unlike a pointer variable. Consequently, what an array "points to" cannot be changed, and it is impossible to assign a value to an array variable. (Array values may be copied, however, e.g., by using the memcpy function.)
[edit]
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 is loaded into memory
Automatic memory allocation: temporary objects can be stored on the stack, and this space is automatically freed and reusable after the block in which they are declared is exited
Dynamic memory allocation: blocks of memory of arbitrary size can be requested at run-time using library functions such as malloc from a region of memory called the heap; these blocks persist until subsequently freed for reuse by calling the library function free

These three approaches are appropriate in different situations and have various tradeoffs. For example, static memory allocation has no allocation overhead, automatic allocation may involve a small amount of overhead, 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 and transient than either static memory or heap space, and dynamic memory allocation allows allocation of objects whose size is known only at run-time. Most C programs make extensive use of all three.

Where possible, automatic or static allocation is usually preferred because the storage is managed by the compiler, freeing the programmer of the potentially error-prone chore of manually allocating and releasing storage. However, many data structures can grow in size at runtime, and since static allocations (and automatic allocations in C89 and C90) must have a fixed size at compile-time, there are many situations in which dynamic allocation must be used. Prior to the C99 standard, variable-sized arrays were a common example of this (see malloc for an example of dynamically allocated arrays).

Automatically and dynamically allocated objects are only initialized if an initial value is explicitly specified; otherwise they initially have indeterminate values (typically, whatever bit pattern happens to be present in the storage, which might not even represent a valid value for that type). If the program attempts to access 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 issue is that heap memory allocation has to be manually synchronized with its actual usage in any program in order for it to be reused as much as possible. For example, if the only pointer to a heap memory allocation goes out of scope or has its value overwritten before free() has been called, then that memory cannot be recovered for later reuse and is essentially lost to the program, a phenomenon known as a memory leak. Conversely, it is possible to release memory too soon and continue to access it; however, since the allocation system can re-allocate or itself use the freed memory, unpredictable behavior is likely to occur. Typically, the symptoms will appear in a portion of the program far removed from the actual error, making it difficult to track down the problem. Such issues are ameliorated in languages with automatic garbage collection.
[edit]
Libraries

The C programming language uses libraries as its primary method of extension. In C, a library is a set of functions contained within a single "archive" file. Each library typically has a header file, which contains the prototypes of the functions contained within the library that may be used by a program, and declarations of special data types and macro symbols used with these functions. In order for a program to use a library, it must include the library's header file, and the library must be linked with the program, which in many cases requires compiler flags (e.g., -lm, shorthand for "math library").

The most common C library is the C standard library, which is specified by the ISO and ANSI C standards and comes with every C implementation (“freestanding” [embedded] C implementations may provide only a subset of the standard library). This library supports stream input and output, memory allocation, mathematics, character strings, and time values.

Another common set of C library functions are those used by applications specifically targeted for Unix and Unix-like systems, especially functions which provide an interface to the kernel. These functions are detailed in various standards such as POSIX and the Single UNIX Specification.

Since many programs have been written in C, there are a wide variety of other libraries available. Libraries are often written in C because C compilers generate efficient object code; programmers then create interfaces to the library so that the routines can be used from higher-level languages like Java, Perl, and Python.
[edit]
Language tools

Tools have been created to help C programmers avoid some of the problems inherent in the language, such as statements with undefined behavior or statements that are not a good practice because they are more likely to result in unintended behavior or run-time errors.

Automated source code checking and auditing are beneficial in any language, and for C many such tools exist, such as Lint. A common practice is to use Lint to detect questionable code when a program is first written. Once a program passes Lint, it is then compiled using the C compiler. Also, many compilers can optionally warn about syntactically valid constructs that are likely to actually be errors. MISRA C is a proprietary set of guidelines to avoid such questionable code, developed for embedded systems.

There are also compilers, libraries and operating system level mechanisms for performing array bounds checking, buffer overflow detection, serialization and automatic garbage collection, that are not a standard part of C.

Tools such as Purify, Valgrind, and linking with libraries containing special versions of the memory allocation functions can help uncover runtime memory errors.
[edit]
Related languages

C has directly or indirectly influenced many later languages such as Java, Perl, PHP, JavaScript, LPC, C# and Unix's C Shell. The most pervasive influence has been syntactical: all of the languages mentioned combine the statement and (more or less recognizably) expression syntax of C with type systems, data models and/or large-scale program structures that differ from those of C, sometimes radically.
When object-oriented languages became popular, C++ and Objective-C were two different extensions of C that provided object-oriented capabilities. Both languages were originally implemented as source-to-source compilers -- source code was translated into C, and then compiled with a C compiler.
The C++ programming language was devised by Bjarne Stroustrup as one approach to providing object-oriented functionality with C-like syntax. C++ adds greater typing strength, scoping and other tools useful in object-oriented programming and permits generic programming via templates. Nearly a superset of C, C++ now supports most of C, with a few exceptions (see Compatibility of C and C++ for an exhaustive list of differences).
Objective-C was originally a very "thin" layer on top of, and remains a strict superset of C that permits object-oriented programming using a hybrid dynamic/static typing paradigm. Objective-C derives its syntax from both C and Smalltalk: syntax that involves preprocessing, expressions, function declarations and function calls is inherited from C, while the syntax for object-oriented features was originally taken from Smalltalk.
The D programming language makes a clean break with C while maintaining the same general syntax, unlike C++, which maintains nearly complete backwards compatibility with C. D abandons a number of features of C which Walter Bright (the designer of D) considered undesirable, including the C preprocessor and trigraphs. Some, but not all, of D's extensions to C overlap with those of C++.

Limbo is a language developed by a team at Bell Labs, and while it retains some of the syntax and the general style of C, it also includes garbage collection and CSP-based concurrency.

Python has a different sort of C heritage. While the syntax and semantics of Python are radically different from C, the most widely used Python implementation, CPython, is an open source C program. This allows C users to extend Python with C, or embed Python into C programs. This close relationship is one of the key factors leading to Python's success as a general-use dynamic language.
Perl is another example of a popular programming language rooted in C. The overall structure of Perl derives broadly from C. The standard Perl implementation is written in C and supports extensions written in C.
Introduction to C Programming Language
C is a general-purpose computer programming language developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system.
Although C was designed for implementing system software, it is also widely used for developing portable application software.
C is one of the most popular programming languages.It is widely used on many different software platforms, and there are few computer architectures for which a C compiler does not exist. C has greatly influenced many other popular programming languages, most notably C++, which originally began as an extension to C.
Getting Started with C
The C program is a set of functions. A C program always starts executing in a special function called main function. Here is the simple but famous "Hello World" program which prints "Hello World" greeting to screen.
1.
#include
2.
main()
3.
{
4.
printf("Hello World!\n");
5.
return 0;
6.
}
The first line is the the #include directive. C program uses this directive to load external function library - stdio is c library which provides standard input/output. printf is a function which is declared in the header file called stdio.h
The next is the main function - the first entry point of all C programs. C program logic starts from the beginning of main function to the its ending.
And finally is the printf function which accepts a string parameter. The printf function is used to print out the message to the screen.

You've learnt how to write the first program in C. Let's go to the next tutorial to explore the power of C programming language. Happy Programming!
C Data Types
Data types are used to store various types of data that is processed by program. Data type attaches with variable to determine the number of bytes to be allocate to variable and valid operations which can be performed on that variable. C supports various data types such as character, integer and floating-point types.
Character Data Type

C stores character type internally as an integer. Each character has 8 bits so we can have 256 different characters values (0-255).

Character set is used to map between an integer value and a character. The most common character set is ASCII.

Let take a look at example of using a variable which hold character 'A'.
01.
#include
02.

03.
void main()
04.
{
05.
char ch = 'A';
06.
printf("%c\n",ch);
07.
ch = 65;// using integer representation
08.
printf("%c\n",ch);
09.
ch = '\x41'; // using hexadecimal representation
10.
printf("%c\n",ch);
11.
ch = '\101'; // using octal representation
12.
printf("%c\n",ch);
13.
}

Here is the output
A
A
A
A
Integer Data Type

Integer data types are used to store numbers and characters. Here is the table of integer data type in various forms:Data Type Memory Allocation Range
signed char 1 byte −27 to 27−1 (−128 to 127)
Unsigned char 1 byte 0 to 28−1 (0 to 255)
short 2 bytes −215 to 215 −1 (−32768 to 32767)
Unsigned short 2 bytes 0 to 216 −1 (0 to 65535)
long int 4 bytes 231 to 231−1 (2,147,483,648 to 2,147,483,647)
int 2 or 4 bytes depending on implementation Range for 2 or 4 bytes as given above

Floating-point Data Type

The floating-point data types are used to represent floating-point numbers. Floating-point data types come in three sizes: float (single precision), double (double precision), and long double (extended precision). The exact meaning of single, double, and extended precision is based on implementation defined. Choosing the right precision for a problem where the choice matters requires understanding of floating point computation.
Floating-point literal

Floating-point literal is double by default. You can use the suffix f or F to get a floating-point literal 3.14f or 3.14F
Type Conversion

Type conversion occurs when an expression has a mixed data types. At this time, the compiler will try to convert from lower to higher type, because converting from higher to lower may cause loss of precision and value.C has following rules for type conversion.
Integer types are lower than floating-point types.
Signed types are lower than unsigned types.
Short whole-number types are lower than longer types.
The hierarchy of data types is as follows: double, float, long, int, short, char.

So based on those rules, we have general rules for type conversion:
Character and short data are promoted to integer.
Unsigned char and unsigned short are converted to unsigned integer.
If the expression includes unsigned integer and any other data type, the other data type is converted to an unsigned integer and the result will be unsigned integer.
If the expression contains long and any other data type, that data type is converted to long and the result will be long.
Float is promoted to double.
If the expression includes long and unsigned integer data types, the unsigned integer is converted to unsigned long and the result will be unsigned long.
If the mixed expression is of the double data type, the other operand is also converted to double and the result will be double.
If the mixed expression is of the unsigned long data type, then the other operand is also converted to double and the result will be double.
Conversion Type Casting

When we want to convert the value of a variable from one type to another we can use type casting. Type casting does not change the actual value of variable. It can be done using a cast operator (unary operator).
C Variables
Defining Variables

A variable is a meaningful name of data storage location in computer memory. When using a variable you refer to memory address of computer.
Naming Variables

The name of variable can be called identifier or variable name in a friendly way. It has to follow these rules:
The name can contain letters, digits and the underscore but the first letter has to be a letter or the underscore. Be avoided underscore as the first letter because it can be clashed with standard system variables.
The length of name can be up to 247 characters long in Visual C++ but 31 characters are usually adequate. Keywords cannot be used as a variable name.

Of course, the variable name should be meaningful to the programming context.
Declaring Variables

To declare a variable you specify its name and kind of data type it can store. The variable declaration always ends with a semicolon, for example:
1.
int counter;
2.
char ch;

You can declare variables at any point of your program before using it. The best practice suggests that you should declare your variables closest to their first point of use so the source code is easier to maintain. In C programming language, declaring a variable is also defining a variable.
Initializing Variables

You can also initialize a variable when you declare it, for example:
1.
int x = 10;
2.
char ch = 'a';
Storage of Variables

Each variable has its own lifetime (the length of time the variable can be accessible) or storage duration. When you declare your variable you implicitly assign it a lifetime. Let take a look at this source code example:
01.
#include
02.

03.
int global_variable = 10;// global variable
04.

05.
void func();
06.

07.
void main()
08.
{
09.
int i;
10.
// test static variable
11.
for(i = 0; i < 5 ; i++) 12. { 13. func(); 14. printf("after %d call \n",i); 15. } 16. } 17. void func() 18. { 19. static int counter = 0;// static variable 20. counter++; 21. printf("func is called %d time(s)\n",counter); 22. 23. int local_variable = 10; 24. 25. } Explanations global_variable is a global variable. It is visible and accessible to all functions. It has static life time (static means variable is retained until the program executes). It is suggested that we should avoid using global variable because it is difficult to maintain, and we don’t know exactly the state of global variable because any functions can change it at any time of program execution. The local_variable and i are only existed until function completed. We cannot access it anymore. In this case it is call automatic lifetimes. In case you want a local variable has static lifetimes, you can use static keyword like counter variable in func(). It retains until program executes even when the func() completed. extern and register keywords You can use extern keyword when declaring a variable or function to imply that the variable is implemented elsewhere and it will be implement later on. register keyword is used when you want a variable which is accessed many time and required fast memory access. Be noted that, declaring a variable with register keyword acts as a directive. It means it does not guarantee the allocation of a register for storing values. Scope of Variables You can define variable in a block of code which specifies by {and} braces. The variable has the scope inside block it is declared. C Operators Arithmetic Operators C programming language supports almost common arithmetic operator such as +,-,* and modulus operator %. Modulus operator (%) returns the remainder of integer division calculation. The operators have precedence rules which are the same rule in math. Here is a C program demonstrate arithmetic operators: 01. #include
02.
/* a program demonstrates C arithmetic operators */
03.
void main(){
04.
int x = 10, y = 20;
05.

06.
printf("x = %d\n",x);
07.
printf("y = %d\n",y);
08.
/* demonstrate = operator + */
09.
y = y + x;
10.
printf("y = y + x; y = %d\n",y);
11.

12.
/* demonstrate - operator */
13.
y = y - 2;
14.
printf("y = y - 2; y = %d\n",y);
15.
/* demonstrate * operator */
16.
y = y * 5;
17.
printf("y = y * 5; y = %d\n",y);
18.

19.
/* demonstrate / operator */
20.
y = y / 5;
21.
printf("y = y / 5; y = %d\n",y);
22.

23.
/* demonstrate modulus operator % */
24.
int remainder = 0;
25.
remainder = y %3;
26.

27.
printf("remainder = y %% 3; remainder = %d\n",remainder);
28.

29.
/* keep console screen until a key stroke */
30.
char key;
31.
scanf(&key);
32.
}

And here is the output
x = 10
y = 20
y = y + x; y = 30
y = y - 2; y = 28
y = y * 5; y = 140
y = y / 5; y = 28
remainder = y % 3; remainder = 1
C Assignment Operators
C assignment operators are used to assigned the value of a variable or expression to a variable. The syntax of assignment operators is:
1.
var = expression;
2.
var = var;

Beside = operator, C programming language supports other short hand format which acts the same assignment operator with additional operator such as +=, -=, *=, /=, %=.
1.
var +=expression; //means
2.
var = var + expression;

Each assignment operator has a priority and they are evaluated from right to left based on its priority. Here is assignment operator and its priority: =, +=, -=, *=, /=, %=.

A simple C program to demonstrate assignment operators:
01.
#include
02.
/* a program demonstrates C assignment operator */
03.
void main(){
04.
int x = 10;
05.

06.
/* demonstrate = operator */
07.
int y = x;
08.
printf("y = %d\n",y);
09.

10.
/* demonstrate += operator */
11.
y += 10;
12.
printf("y += 10;y = %d\n",y);
13.
/* demonstrate -= operator */
14.
y -=5;
15.
printf("y -=5;y = %d\n",y);
16.

17.
/* demonstrate *= operator */
18.
y *=4;
19.
printf("y *=4;y = %d\n",y);
20.

21.
/* demonstrate /= operator */
22.
y /=2;
23.
printf("y /=2;y = %d\n",y);
24.

25.
}

Here is the output:
y = 10
y += 10;y = 20
y -=5;y = 15
y *=4;y = 60
y /=2;y = 30
C Bitwise Operators
Bitwise operators interpret operands as strings of bits. Bit operations are performed on this data to get the bit strings. These bit strings are then interpreted according to data type. There are six bit operators: bitwise AND(&), bitwise OR(|), bitwise XOR(^), bitwise complement(~), left shift(<<), and right shift(>>). We use bitwise operators in some programming contexts because bitwise operations are faster than (+) and (-) operations and significantly faster than (*) and (/) operations. Here is a program which demonstrate C bitwise operator:
01.
#include
02.
/* a demonstration of C bitwise operators */
03.
void main()
04.
{
05.
int d1 = 4,/* 101 */
06.
d2 = 6,/* 110*/
07.
d3;
08.

09.
printf("\nd1=%d",d1);
10.
printf("\nd2=%d",d2);
11.

12.
d3 = d1 & d2; /* 0101 & 0110 = 0100 (=4) */
13.
printf("\n Bitwise AND d1 & d2 = %d",d3);
14.

15.
d3 = d1 | d2;/* 0101 | 0110 = 0110 (=6) */
16.
printf("\n Bitwise OR d1 | d2 = %d",d3);
17.

18.
d3 = d1 ^ d2;/* 0101 & 0110 = 0010 (=2) */
19.
printf("\n Bitwise XOR d1 ^ d2 = %d",d3);
20.

21.
d3 = ~d1; /* ones complement of 0000 0101 is 1111 1010 (-5) */
22.
printf("\n Ones complement of d1 = %d",d3);
23.

24.
d3 = d1<<2;/* 0000 0101 left shift by 2 bits is 0001 0000 */ 25. printf("\n Left shift by 2 bits d1 << 2 = %d",d3); 26. 27. d3 = d1>>2;/* 0000 0101 right shift by 2 bits is 0000 0001 */
28.
printf("\n Right shift by 2 bits d1 >> 2 = %d",d3);
29.
}

And here is the output
d1=4
d2=6
Bitwise AND d1 & d2 = 4
Bitwise OR d1 | d2 = 6
Bitwise XOR d1 ^ d2 = 2
Ones complement of d1 = -5
Left shift by 2 bits d1 << 2 = 16 Right shift by 2 bits d1 >> 2 = 1
C Increment Operators
We can use increment operator to increase or decrease the value of variable. C increment operators support in both prefix and postfix form. Here are syntax of of increment operators:
1.
variable++;
2.
variable--;
3.
++variable;
4.
--variable;

Here is the demonstration program:
01.
#include
02.
/* a program demonstrates C increment operators */
03.
void main(){
04.
int x = 10;
05.
int y = 0;
06.
printf("x = %d\n",x);
07.

08.
/* demonstrate ++ prefix operator */
09.
y = ++x;
10.
printf("y = ++x;y = %d\n",y);
11.

12.
/* demonstrate ++ postfix operator */
13.
y = x++;
14.
printf("y = x++;y = %d\n",y);
15.

16.
/* demonstrate -- prefix operator */
17.
y = --x;
18.
printf("y = --x;y = %d\n",y);
19.

20.
/* demonstrate -- postfix operator */
21.
y = x--;
22.
printf("y = x--;y = %d\n",y);
23.

24.
/* keep console screen until a key stroke */
25.
char key;
26.
scanf(&key);
27.
}

And the output is:
x = 10
y = ++x;y = 11
y = x++;y = 11
y = --x;y = 11
y = x--;y = 11
C Logical Operators
a b a&&b a||b !a
True True True True False
True False False True False
False True False True True
False False False False True
C Relational Operators
Relational operators in C programming language are as follows: <, <=, >, >=, ==, != . They are used in Boolean conditions or expression and returns true or false. Here is a program which demonstrate relational operators:
01.
#include
02.
/* a program demonstrates C relational operators */
03.

04.

05.
void print_bool(bool value){
06.
value == true ? printf("true\n") : printf("false\n");
07.
};
08.

09.
void main(){
10.
int x = 10, y = 20;
11.

12.
printf("x = %d\n",x);
13.
printf("y = %d\n",y);
14.

15.
/* demonstrate == operator */
16.
bool result = (x == y);
17.
printf("bool result = (x == y);");
18.
print_bool(result);
19.

20.
/* demonstrate != operator */
21.
result = (x != y);
22.
printf("bool result = (x != y);");
23.
print_bool(result);
24.

25.
/* demonstrate > operator */
26.
result = (x > y);
27.
printf("bool result = (x > y);");
28.
print_bool(result);
29.

30.
/* demonstrate >= operator */
31.
result = (x >= y);
32.
printf("bool result = (x >= y);");
33.
print_bool(result);
34.

35.
/* demonstrate < operator */ 36. result = (x < y); 37. printf("bool result = (x < y);"); 38. print_bool(result); 39. 40. /* demonstrate <= operator */ 41. result = (x <= y); 42. printf("bool result = (x <= y);"); 43. print_bool(result); 44. 45. 46. /* keep console screen until a key stroke */ 47. char key; 48. scanf(&key); 49. } Here is the output: x = 10 y = 20 bool result = (x == y);false bool result = (x != y);true bool result = (x > y);false
bool result = (x >= y);false
bool result = (x < y);true bool result = (x <= y);true C Ternary Operator C ternary operator is a shorthand of combination of if and return statement. Syntax of ternary operator are as follows: (expression1 ) ? expression2: expression3 If expression1 is true it returns expression2 otherwise it returns expression3. This operator is a shorthand version of this if and return statement: view source print ? 1. if(expression1) 2. return expression2; 3. else 4. return expression3; C Control Flow if Statement f statement is a basic control flow structure of C programming language. if statement is used when a unit of code need to be executed by a condition true or false. If the condition is true, the code in if block will execute otherwise it does nothing. The if statement syntax is simple as follows: 1. if(condition){ 2. /* unit of code to be executed */ 3. } C programming language forces condition must be a boolean expression or value. if statement has it own scope which defines the range over which condition affects, for example: 01. /* all code in bracket is affects by if condition*/ 02. if(x == y){ 03. x++; 04. y--; 05. } 06. /* only expression x++ is affected by if condition*/ 07. if(x == y) 08. x++; 09. y--; In case you want to use both condition of if statement, you can use if-else statement. If the condition of if statement is false the code block in else will be executed. Here is the syntax of if-else statement: 1. if(condition){ 2. /* code block of if statement */ 3. }else{ 4. /* code block of else statement */ 5. } If we want to use several conditions we can use if-else-if statement. Here are common syntax of if-else-if statement: 01. if(condition-1){ 02. /* code block if condition-1 is true */ 03. }else if (condition-2){ 04. /* code block if condition-2 is true */ 05. }else if (condition-3){ 06. /* code block if condition-3 is true */ 07. }else{ 08. /* code block all conditions above are false */ 09. } view source print ? 1. if(x == y){ 2. printf("x is equal y"); 3. } 4. else if (x > y){
5.
printf("x is greater than y");
6.
}else if (x < y){ 7. printf("x is less than y"); 8. } C Switch Statement The switch statement allows you to select from multiple choices based on a set of fixed values for a given expression. Here are the common switch statement syntax: 01. switch(expression){ 02. case value1: /* execute unit of code 1 */ 03. break; 04. case value2: /* execute unit of code 2 */ 05. break; 06. ... 07. default: /* execute default action */ 08. break; 09. } In the switch statement, the selection is determined by the value of an expression that you specify, which is enclosed between the parentheses after the keyword switch. The data type of value which is returned by expression must be an integer value otherwise the statement will not compile. The case constant expression must be an integer value and all values in case statement are equal. When a break statement is executed, it causes execution to continue with the statement following the closing brace for the switch. The break statment is not mandatory, but if you don't put a break statement at the end of the statements for a case, the statements for the next case in sequence will be executed as well, through to whenever another break is found or the end of the switch block is reached. This can lead some unexpected program logics happen. The default statement is the default choice of the switch statement if all cases statement are not satisfy with the expression. The break after the default statements is not necessary unless you put another case statement below it. Here is an example of using C switch statement 01. #include
02.

03.
const int RED = 1;
04.
const int GREEN = 2;
05.
const int BLUE = 3;
06.

07.
void main(){
08.
int color = 1;
09.
printf("Enter an integer to choose a color(red=1,green=2,blue=3):\n");
10.
scanf("%d",&color);
11.

12.
switch(color){
13.
case RED: printf("you chose red color\n");
14.
break;
15.
case GREEN:printf("you chose green color\n");
16.
break;
17.
case BLUE:printf("you chose blue color\n");
18.
break;
19.
default:printf("you did not choose any color\n");
20.
}
21.
}

Here is the output:
Please enter an integer to choose a color(red=1,green=2,blue=3):
2
you chose green color
While Loop Statement
A loop statement allows you to execute a statement or block of statements repeatedly. The while loop is used when you want to execute a block of statements repeatedly with checked condition before making an iteration. Here is syntax of while loop statement:
1.
while (expression) {
2.
// statements
3.
}

This loop executes as long as the given logical expression between parentheses after while is true. When expression is false, execution continues with the statement following the loop block. The expression is checked at the beginning of the loop, so if it is initially false, the loop statement block will not be executed at all. And it is necessary to update loop conditions in loop body to avoid loop forever. If you want to escape loop body when a certain condition meet, you can use break statement

Here is a while loop statement demonstration program:
01.
#include
02.

03.
void main(){
04.
int x = 10;
05.
int i = 0;
06.

07.
// using while loop statement
08.
while(i < x){ 09. i++; 10. printf("%d\n",i); 11. } 12. 13. 14. // when number 5 found, escape loop body 15. int numberFound= 5; 16. int j = 1; 17. while(j < x){ 18. if(j == numberFound){ 19. printf("number found\n"); 20. break; 21. } 22. printf("%d...keep finding\n",j); 23. j++; 24. } 25. 26. } And here is the output: 1 2 3 4 5 6 7 8 9 10 1...keep finding 2...keep finding 3...keep finding 4...keep finding number found do-while Loop Statement do while loop statement allows you to execute code block in loop body at least one. Here is do while loop syntax: 1. do { 2. // statements 3. } while (expression); Here is an example of using do while loop statement: 01. #include
02.
void main(){
03.
int x = 5;
04.
int i = 0;
05.
// using do while loop statement
06.
do{
07.
i++;
08.
printf("%d\n",i);
09.
}while(i < x); 10. 11. } The program above print exactly 5 times as indicated in do while loop body 1 2 3 4 5 for Loop Statement 1. for (initialization_expression;loop_condition;increment_expression){ 2. // statements 3. } There are three parts which is separated by semi-colons in control block of the for loop. initialization_expression is executed before execution of the loop starts. This is typically used to initialize a counter for the number of loop iterations. You can initialize a counter for the loop in this part. The execution of the loop continues until the loop_condition is false. This expression is checked at the beginning of each loop iteration. The increment_expression, is usually used to increment the loop counter. This is executed at the end of each loop iteration. Here is an example of using for loop statement to print an integer five times 01. #include
02.

03.
void main(){
04.
// using for loop statement
05.
int max = 5;
06.
int i = 0;
07.
for(i = 0; i < max;i++){ 08. 09. printf("%d\n",i); 10. 11. } 12. } And the output is 1 2 3 4 5 C break and continue Statements break statement is used to break any type of loop such as while, do while an for loop. break statement terminates the loop body immediately. continue statement is used to break current iteration. After continue statement the control returns to the top of the loop test conditions. Here is an example of using break and continue statement: 01. #include
02.
#define SIZE 10
03.
void main(){
04.

05.
// demonstration of using break statement
06.

07.
int items[SIZE] = {1,3,2,4,5,6,9,7,10,0};
08.

09.
int number_found = 4,i;
10.

11.
for(i = 0; i < SIZE;i++){ 12. 13. if(items[i] == number_found){ 14. 15. printf("number found at position %d\n",i); 16. 17. break;// break the loop 18. 19. } 20. printf("finding at position %d\n",i); 21. } 22. 23. // demonstration of using continue statement 24. for(i = 0; i < SIZE;i++){ 25. 26. if(items[i] != number_found){ 27. 28. printf("finding at position %d\n",i); 29. 30. continue;// break current iteration 31. } 32. 33. // print number found and break the loop 34. 35. printf("number found at position %d\n",i); 36. 37. break; 38. } 39. 40. } Here is the output finding at position 0 finding at position 1 finding at position 2 number found at position 3 finding at position 0 finding at position 1 finding at position 2 number found at position 3 C Function Introduce to C function Define function Function is a block of source code which does one or some tasks with specified purpose. Benefit of using function C programming language supports function to provide modularity to the software. One of major advantage of function is it can be executed as many time as necessary from different points in your program so it helps you avoid duplication of work. By using function, you can divide complex tasks into smaller manageable tasks and test them independently before using them together. In software development, function allows sharing responsibility between team members in software development team. The whole team can define a set of standard function interface and implement it effectively. Structure of function Function header The general form of function header is: 1. return_type function_name(parameter_list) Function header consists of three parts: Data type of return value of function; it can be any legal data type such as int, char, pointer… if the function does not return a value, the return type has to be specified by keyword void. Function name; function name is a sequence of letters and digits, the first of which is a letter, and where an underscore counts as a letter. The name of a function should meaningful and express what it does, for example bubble_sort, And a parameter list; parameter passed to function have to be separated by a semicolon, and each parameter has to indicate it data type and parameter name. Function does not require formal parameter so if you don’t pass any parameter to function you can use keyword void. Here are some examples of function header: 1. /* sort the array of integer a with the 2. specified size and return nothing */ 3. void sort(int a[], int size); 4. 5. /* authenticate user by username and password and return true 6. if user is authenticated */ 7. bool authenticate(char*username,char*password) Function body Function body is the place you write your own source code. All variables declare in function body and parameters in parameter list are local to function or in other word have function scope. Return statement Return statement returns a value to where it was called. A copy of return value being return is made automatically. A function can have multiple return statements. If the void keyword used, the function don’t need a return statement or using return; the syntax of return statement is return expression; Using function How to use the function Before using a function we should declare the function so the compiler has information of function to check and use it correctly. The function implementation has to match the function declaration for all part return data type, function name and parameter list. When you pass the parameter to function, they have to match data type, the order of parameter. Source code example Here is an example of using function. 01. #include
02.

03.
/* functions declaration */
04.

05.
void swap(int *x, int *y);
06.

07.

08.

09.
void main()
10.
{
11.
int x = 10;
12.
int y = 20;
13.

14.
printf("x,y before swapping\n");
15.
printf("x = %d\n",x);
16.
printf("y = %d\n",y);
17.

18.
// using function swap
19.
swap(&x,&y);
20.

21.
printf("x,y after swapping\n");
22.
printf("x = %d\n",x);
23.
printf("y = %d\n",y);
24.

25.
}
26.

27.

28.
/* functions implementation */
29.

30.
void swap(int *x, int *y){
31.
int temp = *x;
32.
*x = *y;
33.
*y = temp;
34.
}

Here is the output
x,y before swapping
x = 10
y = 20
x,y after swapping
x = 20
y = 10
Press any key to continue
Passing Arguments to Function
In order to write correct function you should know how to pass arguments to it. C supports a wide range of mechanisms to allow you to program functions effectively.
Pass by value

With this mechanism, all arguments you pass to function are copied into copy versions and your function work in that copy versions. So parameters does not affects after the function finished.
Pass by pointer

In some programming contexts, you want to change arguments you pass to function. In this case, you can use pass by pointer mechanism. Remember that a pointer is a memory address of a variable. So when you pass a pointer to a function, the function makes a copy of it and changes the content of that memory address, after function finish the parameter is changed with the changes in function body.
Pass an array to function

C allows you pass an array to a function, in this case the array is not copied. The name of array is a pointer which points to the first entry of it. And this pointer is passed to the function when you pass an array to a function.
Source code example of various way to pass arguments to function
01.
#include
02.

03.
/* functions declaration */
04.

05.
/* demonstrate pass by pointer */
06.
void swap(int *x, int *y);
07.

08.
/* demonstrate pass by value */
09.
void swap(int x, int y);
10.

11.
/* demonstrate pass an array to the function */
12.
void bubble_sort(int a[], int size);
13.

14.
void print_array(int a[],int size);
15.

16.
void main()
17.
{
18.
int x = 10;
19.
int y = 20;
20.

21.

22.
printf("x,y before swapping\n");
23.
printf("x = %d\n",x);
24.
printf("y = %d\n",y);
25.

26.
// pass by value
27.
swap(x,y);
28.

29.
printf("x,y after swapping using pass by value\n");
30.
printf("x = %d\n",x);
31.
printf("y = %d\n",y);
32.

33.
// pass by pointer
34.
swap(&x,&y);
35.

36.
printf("x,y after swapping using pass by pointer\n");
37.
printf("x = %d\n",x);
38.
printf("y = %d\n",y);
39.

40.
// declare an array
41.
const int size = 5;
42.
int a[size] = {1,3,2,5,4};
43.

44.
printf("array before sorting\n");
45.
print_array(a,size);
46.

47.
bubble_sort(a,size);
48.

49.
printf("array after sorting\n");
50.
print_array(a,size);
51.

52.

53.
}
54.

55.

56.
/* functions implementation */
57.

58.
void swap(int *x, int *y){
59.
int temp = *x;
60.
*x = *y;
61.
*y = temp;
62.
}
63.

64.
void swap(int x, int y){
65.
int temp = x;
66.
x = y;
67.
y = temp;
68.
}
69.

70.
void bubble_sort(int a[], int size)
71.
{
72.
int i,j;
73.
for(i=0;i<(size-1);i++) 74. for(j=0;j<(size-(i+1));j++) 75. if(a[j] > a[j+1])
76.
swap(&a[j],&a[j+1]);
77.
}
78.

79.
void print_array(int a[],int size)
80.
{
81.

82.
for(int i = 0;i < size; i++) 83. { 84. printf("%d\t",a[i]); 85. printf("\n"); 86. } 87. } Here is the output x,y before swapping x = 10 y = 20 x,y after swapping using pass by value x = 10 y = 20 x,y after swapping using pass by pointer x = 20 y = 10 array before sorting 1 3 2 5 4 array after sorting 1 2 3 4 5 Recursive Function Definition Recursive function is a function which contains a call to itself. Why recursive function Recursive function allows you to divide your complex problem into identical single simple cases which can handle easily. This is also a well-known computer programming technique: divide and conquer. Warning of using recursive function Recursive function must have at least one exit condition that can be satisfied. Otherwise, the recursive function will call itself repeatly until the runtime stack overflows. Example of using recursive function Recursive function is closely related to definitions of functions in mathematics so we can solving factorial problems using recursive function All you know in mathematics the factorial of a positive integer N is defined as follows: N! = N*(N-1)*(N-2)…2*1; Or in a recursive way: N! = 1 if N <=1 and N*(N-1)! if N > 1

The recursive function to calculate factorial
01.
# include
02.

03.
int factorial(unsigned int number)
04.
{
05.
if(number <= 1) 06. return 1; 07. return number * factorial(number - 1); 08. } 09. void main() 10. { 11. int x = 5; 12. printf("factorial of %d is %d",x,factorial(x)); 13. } The output of program factorial of 5 is 120 In theory, all recursive functions can be rewritten by using iteration. In case number of recursive calls exceeded, the runtime stack can be overflow, you have to implement your recursive function using iteration. for example we can rewrite the factorial calculation using iteration as follows: view source print ? 1. int factorial(unsigned int number){ 2. int f = 1; 3. while(number < 0) 4. f *= number--; 5. return f 6. } C Pointer C pointer is a memory address. When you define a variable for example: 1. int x = 10; You specify variable name (x), its data type (integer in this example) and its value is 10. The variable x resides in memory with a specified memory address. To get the memory address of variable x, you use operator & before it. This code snippet print memory address of x 1. printf("memory address of x is %d\n",&x); and in my PC the output is memory address of x is 1310588 Now you want to access memory address of variable x you have to use pointer. After that you can access and modify the content of memory address which pointer point to. In this case the memory address of x is 1310588 and its content is 10. To declare pointer you use asterisk notation (*) after pointer's data type and before pointer name as follows: 1. int *px; Now if you want pointer px to points to memory address of variable x, you can use address-of operator (&) as follows: 1. int *px = &x; After that you can change the content of variable x for example you can increase, decrease x value : 1. *px += 10; 2. printf("value of x is %d\n",x); 3. *px -= 5; 4. printf("value of x is %d\n",x); and the output indicates that x variable has been change via pointer px. value of x is 20 value of x is 15 It is noted that the operator (*) is used to dereference and return content of memory address. In some programming contexts, you need a pointer which you can only change memory address of it but value or change the value of it but memory address. In this cases, you can use const keyword to define a pointer points to a constant integer or a constant pointer points to an integer as follows: 01. int c = 10; 02. int c2 = 20; 03. 04. /* define a pointer and points to an constant integer. 05. pc can point to another integer but you cannot change the 06. content of it */ 07. 08. const int *pc = &c; 09. 10. /* pc++; */ /* cause error */ 11. 12. printf("value of pc is %d\n",pc); 13. 14. pc = &c2; 15. 16. printf("value of pc is %d\n",pc); 17. 18. /* define a constant pointer and points to an integer. 19. py only can point to y and its memory address cannot be changed 20. you can change its content */ 21. 22. int y = 10; 23. int y2 = 20; 24. 25. int const *py = &y; 26. 27. *py++;/* it is ok */ 28. printf("value of y is %d\n",y); 29. 30. /* py = &y2; */ /* cause error */ Here is the output for code snippet value of pc is 1310580 value of pc is 1310576 value of y is 10 C Array Array definition Array by definition is a variable that hold multiple elements which has the same data type. Declaring Arrays We can declare an array by specify its data type, name and the number of elements the array holds between square brackets immediately following the array name. Here is the syntax: 1. data_type array_name[size]; For example, to declare an integer array which contains 100 elements we can do as follows: 1. int a[100]; There are some rules on array declaration. The data type can be any valid C data types including structure and union. The array name has to follow the rule of variable and the size of array has to be a positive constant integer. We can access array elements via indexes array_name[index]. Indexes of array starts from 0 not 1 so the highest elements of an array is array_name[size-1]. Initializing Arrays It is like a variable, an array can be initialized. To initialize an array, you provide initializing values which are enclosed within curly braces in the declaration and placed following an equals sign after the array name. Here is an example of initializing an integer array. 1. int list[5] = {2,1,3,7,8}; Array and Pointer Each array element occupies consecutive memory locations and array name is a pointer that points to the first element. Beside accessing array via index we can use pointer to manipulate array. This program helps you visualize the memory address each array elements and how to access array element using pointer. 01. #include
02.

03.
void main()
04.
{
05.

06.
const int size = 5;
07.

08.
int list[size] = {2,1,3,7,8};
09.

10.
int* plist = list;
11.

12.
// print memory address of array elements
13.
for(int i = 0; i < size;i++) 14. { 15. printf("list[%d] is in %d\n",i,&list[i]); 16. 17. } 18. 19. // accessing array elements using pointer 20. for(i = 0; i < size;i++) 21. { 22. printf("list[%d] = %d\n",i,*plist); 23. 24. /* increase memory address of pointer so it go to the next 25. element of the array */ 26. plist++; 27. } 28. 29. } Here is the output list[0] is in 1310568 list[1] is in 1310572 list[2] is in 1310576 list[3] is in 1310580 list[4] is in 1310584 list[0] = 2 list[1] = 1 list[2] = 3 list[3] = 7 list[4] = 8 You can store pointers in an array and in this case we have an array of pointers. This code snippet use an array to store integer pointer. 1. int *ap[10]; Multidimensional Arrays An array with more than one index value is called a multidimensional array. All the array above is called single-dimensional array. To declare a multidimensional array you can do follow syntax 1. data_type array_name[][][]; The number of square brackets specifies the dimension of the array. For example to declare two dimensions integer array we can do as follows: 1. int matrix[3][3]; Initializing Multidimensional Arrays You can initialize an array as a single-dimension array. Here is an example of initialize an two dimensions integer array: 1. int matrix[3][3] = 2. { 3. {11,12,13}, 4. {21,22,23}, 5. {32,31,33}, 6. }; C Structure Introducing to C structure In some programming contexts, you need to access multiple data types under a single name for easy manipulation; for example you want to refer to address with multiple data like house number, street, zip code, country C supports structure which allows you to wrap one or more variables with different data types. A structure can contain any valid data types like int, char, float even arrays and other structures. Each variable in structure is called a structure member. Defining structure To define a structure, you can use struct keyword. Here is the common syntax of structure definition: struct struct_name{ structure_member }; The name of structure is followed the rule of variable name. Here is an example of defining address structure: 1. struct address{ 2. unsigned int house_number; 3. char street_name[50]; 4. int zip_code; 5. char country[50]; 6. }; It contains house number as an positive integer, street name as a string, zip code as an integer and country as a string. Declaring structure The above example only defines an address structure without create any instance of it. To create or declare a structure you have two ways: The first way is declare a structure follows by structure definition like this : 1. struct struct_name { 2. structure_member; 3. ... 4. } instance_1,instance_2 instance_n; In the second way you can declare your structure instance at a different location in your source code after structure definition. Here is structure declaration syntax : 1. struct struct_name instance_1,instance_2 instance_n; Complex structure Structure can contains arrays or other structures so it is sometimes called complex structure. For example address structure is a complex structure. We can define a complex structure which contains address structure as follows: 1. struct customer{ 2. char name[50]; 3. structure address billing_addr; 4. structure address shipping_addr; 5. }; Accessing structure member To access structure members we can use dot operator (.) between structure name and structure member name as follows: structure_name.structure_member For example to access street name of structure address we do as follows: 1. struct address billing_addr; 2. billing_addr.country = "US"; If the structure contains another structure, we can use dot operator to access nested structure and use dot operator again to access variables of nested structure. 1. struct customer jack; 2. jack.billing_addr.country = "US"; Initializing structure C programming language treats a structure as a custom data type therefore you can initialize a structure like a variable. Here is an example of initialize product structure: 1. struct product{ 2. char name[50]; 3. double price; 4. } book = { "C programming language",40.5}; In above example, we define product structure, then we declare and initialize book structure with its name and price. Structure and pointer A structure can contain pointers as structure members and we can create a pointer to a structure as follows: 1. struct invoice{ 2. char* code; 3. char date[20]; 4. }; 5. 6. struct address billing_addr; 7. struct address *pa = &billing_addr; Shorthand structure with typedef keyword To make your source code more concise, you can use typedef keyword to create a synonym for a structure. This is an example of using typedef keyword to define address structure so when you want to create an instance of it you can omit the keyword struct 01. typedef struct{ 02. unsigned int house_number; 03. char street_name[50]; 04. int zip_code; 05. char country[50]; 06. } address; 07. 08. address billing_addr; 09. address shipping_addr; Copy a structure into another structure One of major advantage of structure is you can copy it with = operator. The syntax as follows 1. struct_intance1 = struct_intance2 be noted that some old C compilers may not supports structure assignment so you have to assign each member variables one by one. Structure and sizeof function sizeof is used to get the size of any data types even with any structures. Let's take a look at simple program: 01. #include
02.

03.
typedef struct __address{
04.
int house_number;// 4 bytes
05.
char street[50]; // 50 bytes
06.
int zip_code; // 4 bytes
07.
char country[20];// 20 bytes
08.

09.
} address;//78 bytes in total
10.

11.
void main()
12.
{
13.
// it returns 80 bytes
14.
printf("size of address is %d bytes\n",sizeof(address));
15.
}

You will never get the size of a structure exactly as you think it must be. The sizeof function returns the size of structure larger than it is because the compiler pads struct members so that each one can be accessed faster without delays. So you should be careful when you read the whole structure from file which were written from other programs.
Source code example of using C structure

In this example, we will show you how to use structure to wrap student information and manipulate it by reading information to an array of student structure and print them on to console screen.
01.
#include
02.

03.
typedef struct _student{
04.
char name[50];
05.
unsigned int mark;
06.
} student;
07.

08.

09.

10.
void print_list(student list[], int size);
11.
void read_list(student list[], int size);
12.

13.

14.

15.
void main(){
16.

17.
const int size = 3;
18.
student list[size];
19.

20.
read_list(list,size);
21.

22.
print_list(list,size);
23.

24.

25.
}
26.

27.
void read_list(student list[], int size)
28.
{
29.
printf("Please enter the student information:\n");
30.

31.
for(int i = 0; i < size;i++){ 32. printf("\nname:"); 33. scanf("%S",&list[i].name); 34. 35. printf("\nmark:"); 36. scanf("%U",&list[i].mark); 37. } 38. 39. } 40. 41. void print_list(student list[], int size){ 42. printf("Students' information:\n"); 43. 44. for(int i = 0; i < size;i++){ 45. printf("\nname: %s, mark: %u",list[i].name,list[i].mark); 46. } 47. } Here is program's output Please enter the student information: name:Jack mark:5 name:Anna mark:7 name:Harry mark:8 Students' information: name: J, mark: 5 name: A, mark: 7 name: H, mark: 8 C String String Definition C does not have a string type as other modern programming languages. C only has character type so a C string is defined as an array of characters or a pointer to characters. Null-terminated String String is terminated by a special character which is called as null terminator or null parameter (/0). So when you define a string you should be sure to have sufficient space for the null terminator. In ASCII table, the null terminator has value 0. Declaring String As in string definition, we have two ways to declare a string. The first way is, we declare an array of characters as follows: 1. char s[] = "string"; And in the second way, we declare a string as a pointer point to characters: 1. char* s = "string"; Declaring a string in two ways looks similar but they are actually different. In the first way, you declare a string as an array of character, the size of string is 7 bytes including a null terminator. But in the second way, the compiler will allocate memory space for the string and the base address of the string is assigned to the pointer variable s. Looping Through a String You can loop through a string by using a subscript. Here is an example of looping through a string using a subscript: 1. // loop through a string using a subscript 2. char s[] = "C string"; 3. int i; 4. for(i = 0; i < sizeof(s);i++) 5. { 6. printf("%c",s[i]); 7. } You can also use a pointer to loop through a string. You use a char pointer and point it to the first location of the string, then you iterate it until the null terminator reached. 1. // loop through a string using a pointer 2. char* ps = s; 3. while(*ps != '\0'){ 4. printf("%c",*ps); 5. ps++; 6. } Passing a String to Function A formal way to pass a string to a function is passing it as a normal array. Dynamic Memory Allocation Introduce to dynamic memory allocation In some programming contexts, you want to process data but dont know what size of it is. For example, you read a list of students from file but dont know how many students record there. Yes, you can specify the enough maximum size for the the array but it is not efficient in memory management. C provides you a powerful and flexible way to manage memory allocation at runtime. It is called dynamic memory allocation. Dynamic means you can specify the size of data at runtime. C programming language provides a set of standard functions prototype to allow you to handle memory effectively. With dynamic memory allocation you can allocate and free memory as needed. Getting to know the size of data Before allocating memory, we need to know the way to identify the size of each data so we can allocate memory correctly. We can get the size of data by using sizeof() function. sizeof() function returns a size_t an unsigned constant integer. For example to get the size of integer type you can do as follows: 1. sizeof(int); It returns 4 bytes in typical 32 bit machines. Here is a simple program which prints out the size of almost common C data type. 01. #include
02.

03.
typedef struct __address{
04.
int house_number;
05.
char street[50];
06.
int zip_code;
07.
char country[20];
08.

09.
} address;
10.

11.
void main()
12.
{
13.

14.
printf("size of int is %d byte(s)\n",sizeof(int));
15.
printf("size of unsigned int is %d byte(s)\n",sizeof(unsigned int));
16.
printf("size of short is %d byte(s)\n",sizeof(short));
17.
printf("size of unsigned short is %d byte(s)\n",sizeof(unsigned short));
18.
printf("size of long is %d byte(s)\n",sizeof(long));
19.

20.
printf("size of char is %d byte(s)\n",sizeof(char));
21.

22.
printf("size of float is %d byte(s)\n",sizeof(float));
23.
printf("size of double is %d byte(s)\n",sizeof(double));
24.

25.
printf("size of address is %d byte(s)\n",sizeof(address));
26.
}

And you can see the output:
size of int is 4 byte(s)
size of unsigned int is 4 byte(s)
size of short is 2 byte(s)
size of unsigned short is 2 byte(s)
size of long is 4 byte(s)
size of char is 1 byte(s)
size of float is 4 byte(s)
size of double is 8 byte(s)
size of address is 80 byte(s)
Allocating memory

We use malloc() function to allocate memory. Here is the function interface:

void * malloc(size_t size);

malloc function takes size_t as its argument and returns a void pointer. The void pointer is used because it can allocate memory for any type. The malloc function will return NULL if requested memory couldnt be allocated or size argument is equal 0. Here is an example of using malloc function to allocate memory:
1.
int* pi;
2.
int size = 5;
3.
pi = (int*)malloc(size * sizeof(int));

sizeof(int) return size of integer (4 bytes) and multiply with size which equals 5 so pi pointer now points to the first byte of 5 * 4 = 20 bytes memory block. We can check whether the malloc function allocate memory space is successful or not by checking the return value.
1.
if(pi == NULL)
2.
{
3.
fprintf(stderr,"error occurred: out of memory");
4.
exit(EXIT_FAILURE);
5.
}

Beside malloc function, C also provides two other functions which make convenient ways to allocate memory:
1.
void *calloc(size_t num, size_t size);
2.
void *realloc(void *ptr, size_t size);

calloc function not only allocates memory like malloc but also allocates memory for a group of objects which is specified by num argument.

realloc function takes in the pointer to the original area of memory to extend and how much the total size of memory should be.
Freeing memory

When you use malloc to allocate memory you implicitly get the memory from a dynamic memory pool which is called heap. The heap is limited so you have to deallocate or free the memory you requested when you don't use it in any more. C provides free function to free memory. Here is the function prototype:
1.
void free(void *ptr);

You should always use malloc and free as a pair in your program to a void memory leak.

No comments: