do your search here :) :-

Google
 

Thursday, January 24, 2008

Operators in C and C++

Operators in C and C++

Operator precedence
The following is a table that lists the
precedence and associativity of all the operators in the C++ programming language. Operators are listed top to bottom in descending precedence and operators that are on the same row are evaluated with the same precedence, in the given direction.
The syntax of expressions in C and C++ is specified by a
context-free grammar. The table given here has been inferred from the grammar.
A precedence table, while mostly adequate, cannot resolve a few details. In particular, note that the
ternary operator allows any arbitrary expression as its middle operand, despite being listed as having higher precedence than the assignment and comma operators. Thus a ? b , c : d is interpreted as a ? (b, c) : d, and not as the meaningless (a ? b), (c : d). Also, note that the immediate, unparenthesized result of a C cast expression cannot be the operand of sizeof. Therefore, sizeof (int) * x is interpreted as (sizeof(int)) * x and not sizeof ((int) *x).
Operator(s)
Description
Associativity
::
Scope resolution (C++ only)
Left-to-Right
++ --()[].->
Postfix increment and decrementFunction callArray subscriptingElement selection by referenceElement selection through pointer
++ --+ -! ~(type)*&sizeofnew new[]delete delete[]
Prefix increment and decrementUnary plus and minusLogical NOT and bitwise NOTType castIndirection (dereference)Address-of (reference)Size-ofDynamic memory allocation (C++ only)Dynamic memory deallocation (C++ only)
Right-to-Left
.* ->*
Pointer to member (C++ only)
Left-to-Right
* / %
Multiplication, division, and modulus (remainder)
+ -
Addition and subtraction
<< >>
Bitwise left shift and right shift
< <=> >=
Relational “less than” and “less than or equal to”Relational “greater than” and “greater than or equal to”
== !=
Relational “equal to” and “not equal to”
&
Bitwise AND
^
Bitwise XOR (exclusive or)

Bitwise OR (inclusive or)
&&
Logical AND

Logical OR
c?t:f
Ternary conditional (see ?:)
Right-to-Left
=+= -=*= /= %=<<= >>=&= ^= =
Direct assignmentAssignment by sum and differenceAssignment by product, dividend, and remainderAssignment by bitwise left shift and right shiftAssignment by bitwise AND, XOR, and OR
throw
Throw operator (exceptions throwing, C++ only)
Not available
,
Comma
Left-to-Right

[edit]

Impulse C Overview

Impulse C includes a compiler and related function library intended for development of FPGA-based applications. Impulse C is compatible with standard ANSI C, allowing standard C tools to be used for designing and debugging applications targeting FPGAs. The Impulse C compiler accepts a subset of C and generates FPGA hardware in the form of Hardware Description Language (HDL) files. Impulse C allows embedded systems designers and software programmers to target FPGA devices for C-language application acceleration.
Impulse C is distinct from standard C in that it provides a parallel
programming model for mixed processor and FPGA platforms. For this purpose, Impulse C includes extensions to C, in the form of a small set of functions and datatypes, allowing applications written in standard C to be mapped efficiently onto coarse-grained parallel architectures that may include standard processors along with programmable FPGA hardware.
The Impulse C tools include hardware/software co-simulation tools as well as C-to-
RTL scheduling/optimizing technology used to map application elements to hardware via FPGA logic synthesis tools.

Impulse C v2.20 tools

[edit] Programming Model
Impulse C supports a variant of the
Communicating Sequential Processes (CSP) programming model, while remaining compatible with standard C tools such as debuggers and profilers. Impulse C is intended to simplify the creation of highly parallel algorithms, including mixed software/hardware algorithms, through the use of well-defined data communication, message passing and synchronization mechanisms. Impulse C is designed for dataflow-oriented, streaming applications, but is also designed to support alternate programming models including the use of shared memory as a communication mechanism.
In an Impulse C streaming application, hardware and software processes communicate primarily through buffered data streams that are implemented directly in hardware. This buffering of data, which is implemented using dual-clock
FIFOs generated by the compiler, makes it possible to write parallel applications at a relatively high level of abstraction, without the cycle-by-cycle synchronization that would otherwise be required.
Using Impulse C, an application can be partitioned to create a multiple-process implementation that is partitioned into hardware and software components, or implemented entirely within an FPGA device. For example, an image filtering application could be described using Impulse C as a collection of parallel, pipelined processes, each of which has been described using one or more C subroutines.
On the software side of the application, for example in an embedded FPGA processor, Impulse C library functions are used to open and close data streams, read or write data on the streams and, if desired, send status messages or poll for results. For processor-to-FPGA communications, stream reads and writes can be specified as operations that take advantage of FPGA-specific, internal or external bus interfaces.
On the hardware side of the application, Impulse C library functions and other C statements are compiled to generate equivalent, parallel hardware implementations in the form of synthesizable HDL files. These files are processed by FPGA tools to create FPGA hardware bitmaps.
At the heart of the Impulse C streaming programming model are processes and streams. Processes are independently synchronized, concurrently executing segments of an application. Hardware processes are written using a subset of standard C and perform the work of an application by accepting data, performing computations and generating outputs. In a typical application, data flows from process to process by means of buffered streams, or in some cases by means of messages and/or shared memories. The characteristics of each stream, including the width and depth of the generated FIFOs, may be specified in the C application.

Parsing and processing C++ source code

It is relatively difficult to write a good C++ parser with classic parsing algorithms such as LALR(1).[5] This is partly because the C++ grammar is not LALR. Because of this, there are very few tools for analyzing or performing non-trivial transformations (e.g., refactoring) of existing code. One way to handle this difficulty is to choose a different syntax, such as Significantly Prettier and Easier C++ Syntax, which is LALR(1) parsable. More powerful parsers, such as GLR parsers, can be substantially simpler (though slower).
Parsing (in the literal sense of producing a syntax tree) is not the most difficult problem in building a C++ processing tool. Such tools must also have the same understanding of the meaning of the identifiers in the program as a compiler might have. Practical systems for processing C++ must then not only parse the source text, but be able to resolve for each identifier precisely which definition applies (e.g. they must correctly handle C++'s complex scoping rules) and what its type is, as well as the types of larger expressions.
Finally, a practical C++ processing tool must be able to handle the variety of C++ dialects used in practice (such as that supported by the
GNU C compiler and that of Microsoft's Visual C++) and implement appropriate analyzers, source code transformers, and regenerate source text. Combining advanced parsing algorithms such as GLR with symbol table construction and program transformation machinery can enable the construction of arbitrary C++ tools.

[edit] Problems and controversies

[edit] Standards compliance
Producing a reasonably standards-compliant C++ compiler has proven to be a difficult task for compiler vendors in general. For many years, different C++ compilers implemented the C++ language to different levels of compliance to the standard, and their implementations varied widely in some areas such as
partial template specialization. Recent releases of most popular C++ compilers support almost all of the C++ 1998 standard.[6]
One particular point of contention is the export keyword, intended to allow template definitions to be separated from their declarations. The first compiler to implement export was Comeau C/C++, in early 2003 (5 years after the release of the standard); in 2004, the beta compiler of Borland C++ Builder X was also released with export. Both of these compilers are based on the EDG C++ front end. It should also be noted that many C++ books provide example code using the keyword export (for example, Beginning ANSI C++ by Ivor Horton) which will not compile in most compilers, but there is no reference to the problem with the keyword export mentioned. Other compilers such as GCC do not support it at all. Herb Sutter, secretary of the C++ standards committee, recommended that export be removed from future versions of the C++ standard, [7] but finally the decision was made to retain it.[8]
In order to give compiler vendors greater freedom, the C++ standards committee decided not to dictate the implementation of name mangling, exception handling, and other implementation-specific features. The downside of this decision is that object code produced by different compilers is expected to be incompatible. There are, however, third party standards for particular machines or operating systems which attempt to standardize compilers on those platforms (for example C++ ABI[9]); some compilers adopt a secondary standard for these items.

[edit] Incompatibility with C
For more details on this topic, see
Compatibility of C and C++.
C++ is often considered to be a superset of C, but this is not strictly true.
[13] Most C code can easily be made to compile correctly in C++, but there are a few differences that cause some valid C code to be invalid in C++, or to behave differently in C++.
One commonly encountered difference is that C allows implicit conversion from void* to other pointer types, but C++ does not. So, the following is valid C code:
int *i = malloc(sizeof(int) * 5); /* Implicit conversion from void* to int* */
... but to make it work in both C and C++ one would need to use an explicit cast:
int *i = (int *) malloc(sizeof(int) * 5);
...and in C++-only code, the static cast is recommended:
int *i = static_cast(malloc(sizeof(int) * 5));
C++ also makes a small change in the behavior of the "conditional" operator. Consider:
// The interpretation of the following expression is different in C and C++
bool flag = xxxx;
int a;
flag ? a=2 : a=3;

// In C the precedence of ? and : are strictly higher than all assignment operators
// so the equation is grouped as follows, because ?: beats =
(flag ? (a=2) : a) = 3;

// The C++ grammar allows an assignment as the else-part, so it's interpreted as:
( flag ? (a=2) : (a=3) );
So in essence, the the "?" and ":" operators have different precedence levels in C++, the "?" placed higher than assignment operators, and the ":" is lower.
Another common portability issue is that C++ defines many new keywords, such as new and class, that may be used as identifiers (e.g. variable names) in a C program.
Some incompatibilities have been removed by the latest
(C99) C standard, which now supports C++ features such as // comments and mixed declarations and code. However, C99 introduced a number of new features that C++ does not support (such as variable-length arrays, native complex-number types, and compound literals), so the languages may be diverging more than they are converging. However, at least some of the new C99 features will likely be included in the next version of the C++ standard, C++0x.
In order to intermix C and C++ code, any C code which is to be called from/used in C++ must be declared with C linkage by placing it within an extern "C" { ... } block.

Inheritance

Inheritance allows one data type to acquire properties of other data types. Inheritance from a base class may be declared as public, protected, or private. This access specifier determines whether unrelated and derived classes can access the inherited public and protected members of the base class. Only public inheritance corresponds to what is usually meant by "inheritance". The other two forms are much less frequently used. If the access specifier is omitted, inheritance is assumed to be private for a class base and public for a struct base. Base classes may be declared as virtual; this is called virtual inheritance. Virtual inheritance ensures that only one instance of a base class exists in the inheritance graph, avoiding some of the ambiguity problems of multiple inheritance.
Multiple inheritance is a C++ feature sometimes considered controversial. Multiple inheritance allows a class to be derived from more than one base class; this can result in a complicated graph of inheritance relationships. For example, a "Flying Cat" class can inherit from both "Cat" and "Flying Mammal". Some other languages, such as Java or C#, accomplish something similar (although more limited) by allowing inheritance of multiple interfaces while restricting the number of base classes to one (interfaces, unlike classes, provide only declarations of member functions, no implementation or member data).

[edit] Polymorphism
See also:
Polymorphism in object-oriented programming
Polymorphism enables one common interface for many implementations, and for objects to act differently under different circumstances.
C++ supports several kinds of static (
compile-time) and dynamic (run-time) polymorphism. Compile-time polymorphism does not allow for certain run-time decisions, while run-time polymorphism typically incurs a performance penalty.

[edit] Static polymorphism

[edit] Function overloading
Function overloading allows programs to declare multiple functions having the same name (but with different arguments). The functions are distinguished by the number and/or types of their formal parameters. Thus, the same function name can refer to different functions depending on the context in which it is used. The type returned by the function is not used to distinguish overloaded functions.

[edit] Default arguments
Default arguments are used when defining a different function is not needed when supplying a default value for an argument will suffice.

[edit] Class and function templates
Templates in C++ provide a sophisticated mechanism for writing generic, polymorphic code. In particular, through the Curiously Recurring Template Pattern it's possible to implement a form of static polymorphism that closely mimics the syntax for overriding virtual methods (a dynamic polymorphism technique described below). Since C++ templates are type-aware and Turing-complete they can also be used to let the compiler resolve recursive conditionals and generate substantial programs through template metaprogramming.

[edit] Dynamic polymorphism

[edit] Inheritance
Variable pointers (and references) to a base class type in C++ can refer to objects of any derived classes of that type in addition to objects exactly matching the variable type. This allows arrays and other kinds of containers to hold pointers to objects of differing types. Because assignment of values to variables usually occurs at run-time, this is necessarily a run-time phenomenon.
C++ also provides a dynamic_cast operator, which allows the program to safely attempt conversion of an object into an object of a more specific object type (as opposed to conversion to a more general type, which is always allowed). This feature relies on
run-time type information (RTTI). Objects known to be of a certain specific type can also be cast to that type with static_cast, a purely compile-time construct which is faster and does not require RTTI.

[edit] Virtual member functions
Ordinarily when a method in a derived class
overrides a method in a base class, the method to call is determined by the type of the object. A given method is overridden when there exists no difference, in the number or type of parameters, between two or more definitions of that method. Hence, at compile time it may not be possible to determine the type of the object and therefore the correct function to call, given only a base class pointer; the decision is therefore put off until runtime. This is called dynamic dispatch. Virtual member functions or methods allow the most specific implementation of the function to be called, according to the actual run-time type of the object. In C++, this is commonly done using virtual function tables. If the object type is known, this may be bypassed by prepending a fully qualified class name before the function call, but in general calls to virtual functions are resolved at run time.
In addition to standard member functions, operator overloads and destructors can also be virtual. A general rule of thumb is that if any functions in the class are virtual, the destructor should be as well. As the type of an object at its creation is known at compile time, constructors, and by extension copy constructors, can not be virtual. Nontheless a situation may arise where a copy of an object needs to be created when a pointer to a derived object is passed as a pointer to a base object. In such a case a common solution is to create a Clone() (or similar) method and declare that as virtual. The Clone() method creates and returns a copy of the derived class when called.
A member function can also be made "pure virtual" by appending it with = 0 after the closing bracket and before the semicolon. Objects can not be created of a class with a pure virtual function and are called abstract data types. Such abstract data types can only be derived from. Any derived class inherits the virtual function as pure and must override it (and all other pure virtual functions) with a non-pure virtual function for objects to be created from the derived class. An attempt to create an object from a class with a pure virtual function or inherited pure virtual function will be flagged as a compile-time error.
An example:
#include

class Bird // the "generic" base class
{
public:
virtual void OutputName() {std::cout << "a bird";}
virtual ~Bird() {}
};

class Swan : public Bird // Swan derives from Bird
{
public:
void OutputName() {std::cout << "a swan";} // overrides virtual function
};

int main()
{
Swan mySwan; // Creates a swan.

Bird* myBird = &mySwan; // Declares a pointer to a generic Bird,
// and sets it pointing to a newly created Swan.

myBird->OutputName(); // This will output "a swan", not "a bird".

return 0;
}
This example program makes use of virtual functions, polymorphism, and inheritance to derive new, more specific objects from a base class. In this case, the base class is a Bird, and the more specific Swan is made.

Operators and operator overloading

C++ provides more than 30 operators, covering basic arithmetic, bit manipulation, indirection, comparisons, logic and more. Almost all operators can be overloaded for user-defined types, with a few notable exceptions such as member access (. and .*). The rich set of overloadable operators is central to using C++ as a domain specific language. As a simple example, a class that represents a matrix could overload the multiplication (*) and other arithmetic operators, allowing it to be treated by application code similarly to the standard numerical types.:
matrix A, B;
matrix C = A * B;
The overloadable operators are also an essential part of many advanced C++ programming techniques, such as
smart pointers.
Overloading an operator does not change the precedence of calculations involving the operator, nor does it change the number of operands that the operator uses (any operand may however be ignored).


Templates
See also:
generic programming and template metaprogramming
Templates are different from macros: while both of these compile-time language features can be used to produce conditional compilation, templates are not restricted to lexical substitution. Templates have an awareness of the semantics and type system of their companion language as well as all compile-time type definitions and can perform high-level operations including programmatic flow control based on evaluation of strictly type-checked parameters. Macros are capable of conditional control over compilation based on predetermined criteria but cannot instantiate new types, recurse or perform type evaluation and in effect are limited to pre-compilation text-substitution and text-inclusion/exclusion. In other words, macros can control compilation flow based on pre-defined symbols but cannot, unlike templates, independently instantiate new symbols. Templates are a tool for static
polymorphism (see below) and generic programming. For example, a template replacing the common, but dangerous, macro #define max(x,y) ((x)>(y)?(x):(y)):
template
const T& max(const T& x, const T& y)
{
return x > y ? x : y;
}
This can be found in the algorithm header as std::max(). Traditionally the keyword class may also be used in place of typename.
In addition, templates are a compile time mechanism in C++ which is
Turing-complete, meaning that any computation expressible by a computer program can be computed, in some form, by a template metaprogram prior to runtime.
In summary, defining a template for a function or class is the equivalent of defining a function or class for each type that can be used as an argument, but does not require prior knowledge of which types will be used.

[edit] Objects
Main article:
C++ structures and classes
C++ introduces some object-oriented (OO) features to C. It offers classes, which provide the four features commonly present in OO (and some non-OO) languages: abstraction, encapsulation, inheritance and polymorphism. Objects are instances of classes created at runtime. Think of the class as a template from which many different individual objects may be generated as a program runs.

[edit] Encapsulation
Encapsulation is the grouping together of data and functionality. C++ implements encapsulation by allowing all members of a class to be declared as either public, private, or protected. A public member of the class is accessible to any function. A private member is accessible only to functions that are members of that class and to functions and classes explicitly granted access permission by the class ("friends"). A protected member is accessible to members of classes that inherit from the class in addition to the class itself and any friends.
The OO principle is that all of the functions (and only the functions) that access the internal representation of a type should be encapsulated within the type definition. C++ supports this (via member functions and friend functions), but does not enforce it: the programmer can declare parts or all of the representation of a type to be public, and is also allowed to make public entities that are not part of the representation of the type. Because of this, C++ supports not just OO programming but other weaker decomposition paradigms, like
modular programming.
It is generally considered good practice to make all
data private or protected, and to make public only those functions that are part of a minimal interface for users of the class. This hides all the details of data implementation, allowing the designer to later fundamentally change the implementation without changing the interface in any way.

C++

C++ (pronounced /ˌsiːˌplʌsˈplʌs/) is a general-purpose programming language. C++ is regarded as a mid-level language, as it comprises a combination of both high-level and low-level language features.[1] It is a statically typed, free-form, multi-paradigm, usually compiled language supporting procedural programming, data abstraction, object-oriented programming, and generic programming.
Bjarne Stroustrup developed C++ in 1979 at Bell Labs as an enhancement to the C programming language and named it "C with Classes". In 1983 it was renamed to C++. Enhancements started with the addition of classes, followed by, among other features, virtual functions, operator overloading, multiple inheritance, templates, and exception handling. The C++ programming language standard was ratified in 1998 as ISO/IEC 14882:1998, the current version of which is the 2003 version, ISO/IEC 14882:2003. A new version of the standard (known informally as C++0x) is being developed.

Language standard
After years of work, a joint
ANSIISO committee standardized C++ in 1998 (ISO/IEC 14882:1998). For some years after the official release of the standard, the committee processed defect reports, and published a corrected version of the C++ standard in 2003. In 2005, a technical report, called the "Library Technical Report 1" (often known as TR1 for short) was released. While not an official part of the standard, it gives a number of extensions to the standard library which are expected to be included in the next version of C++. Support for TR1 is growing in almost all currently maintained C++ compilers.
While the C++ language is royalty-free, the standard document itself is not freely available.

[edit] Etymology
According to Stroustrup: "the name signifies the
evolutionary nature of the changes from C".[3] During C++'s development period, the language had been referred to as "new C", then "C with Classes". The final name is credited to Rick Mascitti (mid-1983) and was first used in December 1983. When Mascitti was questioned informally in 1992 about the naming, he indicated that it was given in a tongue-in-cheek spirit. He never thought that it would become the formal name of the language.[citation needed] It stems from C's "++" operator (which increments the value of a variable after evaluating it) and a common naming convention of using "+" to indicate an enhanced computer program. ABCL/c+ was the name of an earlier, unrelated programming language.

[edit] Philosophy
In
The Design and Evolution of C++ (1994), Bjarne Stroustrup describes some rules that he uses for the design of C++:
C++ is designed to be a
statically typed, general-purpose language that is as efficient and portable as C
C++ is designed to directly and comprehensively support multiple programming styles (
procedural programming, data abstraction, object-oriented programming, and generic programming)
C++ is designed to give the programmer choice, even if this makes it possible for the programmer to choose incorrectly
C++ is designed to be as compatible with C as possible, therefore providing a smooth transition from C
C++ avoids features that are platform specific or not general purpose
C++ does not incur overhead for features that are not used (the "zero-overhead principle")
C++ is designed to function without a sophisticated programming environment
Inside the C++ Object Model (Lippman, 1996) describes how compilers may convert C++ program statements into an in-memory layout. Compiler authors are, however, free to implement the standard in their own manner.

[edit] Standard library
The 1998
ANSI/ISO C++ standard consists of two parts: the core language and the C++ standard library; the latter includes most of the Standard Template Library (STL) and a slightly modified version of the C standard library. Many C++ libraries exist which are not part of the standard, and, using linkage specification, libraries can even be written in languages such as C, Fortran, Pascal, or BASIC. Which of these are supported is compiler dependent.
The C++ standard library incorporates the C standard library with some small modifications to make it work better with the C++ language. Another large part of the C++ library is based on the STL. This provides such useful tools as
containers (for example vectors and lists), iterators (generalized pointers) to provide these containers with array-like access and algorithms to perform operations such as searching and sorting. Furthermore (multi)maps (associative arrays) and (multi)sets are provided, all of which export compatible interfaces. Therefore it is possible, using templates, to write generic algorithms that work with any container or on any sequence defined by iterators. As in C, the features of the library are accessed by using the #include directive to include a standard header. C++ provides 69 standard headers, of which 19 are deprecated.
Using the standard library — for example, using std::vector or std::string instead of a C-style array — can help lead to safer and more scalable software.
The STL was originally a third-party library from
HP and later SGI, before its incorporation into the C++ standard. The standard does not refer to it as "STL", as it is merely a part of the standard library, but many people still use that term to distinguish it from the rest of the library (input/output streams, internationalization, diagnostics, the C library subset, etc.).
Most C++ compilers provide an implementation of the C++ standard library, including the STL. Compiler-independent implementations of the STL, such as
STLPort, also exist. Other projects also produce various custom implementations of the C++ standard library and the STL with various design goals.

[edit] Hello world program
The following is a
Hello world program which uses the C++ standard library stream facility to write a message to standard output.[4]
#include // provides std::cout

int main()
{
std::cout << "Hello, world!\n";
}

Tools for mitigating issues with C

Tools have been created to help C programmers avoid some of the problems inherent in the language.
Automated source code checking and auditing are beneficial in any language, and for C many such tools exist, such as
Lint. A common practice is to use Lint to detect questionable code when a program is first written. Once a program passes Lint, it is then compiled using the C compiler.
There are also compilers, libraries and operating system level mechanisms for performing array bounds checking,
buffer overflow detection, serialization and automatic garbage collection, that are not a standard part of C.
Cproto is a program that will read a C source file and output prototypes of all the functions within the source file. This program can be used in conjunction with the make command to create new files containing prototypes each time the source file has been changed. These prototype files can be included by the original source file (e.g., as "filename.p"), which reduces the problems of keeping function definitions and source files in agreement.
It should be recognized that these tools are not a panacea. Because of C's flexibility, some types of errors involving misuse of variadic functions, out-of-bounds array indexing, and incorrect memory management cannot be detected on some architectures without incurring a significant performance penalty. However, some common cases can be recognized and accounted for.

[edit] Related languages
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 preprocessors -- source code was translated into C, and then compiled with a C compiler.

[edit] C++
Main article:
C++
Bjarne Stroustrup devised the C++ programming language 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).

[edit] D
Main article:
D (programming language)
Unlike C++, which maintains nearly complete backwards compatibility with C, D makes a clean break with C while maintaining the same general syntax. It abandons a number of features of C which the designer of D considered undesirable, including the C preprocessor and trigraphs, and adds some, but not all, of the extensions of C++.

[edit] Objective-C
Main article:
Objective-C
Objective-C is a very "thin" layer on top of, and is 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 is taken from Smalltalk.

[edit] Other influences
C has directly or indirectly influenced many later languages such as
Java, C#, Perl, PHP, JavaScript, 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

Data structures

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 value that points to no valid location (it is often represented by address zero). 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.
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.

[edit] Arrays
Array types in C are always one-dimensional and, 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 (see the "Criticism" article), and can lead to various repercussions: illegal memory accesses, corruption of data, buffer overrun, run-time exceptions, etc.
C does not have a special provision for declaring multidimensional arrays, but rather relies on recursion within the type system to declare arrays of arrays, which effectively accomplishes the same thing. The index values of the resulting "multidimensional array" can be thought of as increasing in
row-major order.

[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 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 sizeof array), 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 C's function calls use
pass-by-value semantics, arrays are in effect passed by reference.
The number of elements in a declared array a can be determined as sizeof a / sizeof a[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. Note how the last line contains the strange code i[x] = 1;, which has the index variable i apparently interchanged with the array variable x. This last line might be found in
obfuscated C C code./* x designates an array */
x[i] = 1;
*(x + i) = 1;
*(i + x) = 1;
i[x] = 1; /* strange, but correct: i[x] is equivalent to *(i + x) */
However, there is a distinction to be made between arrays and pointer variables. Even though the name of an array is in most expression contexts converted to a pointer (to its first element), this pointer does not itself occupy any storage. Consequently, you cannot change what an array "points to", and it is impossible to assign to an array. (Arrays may however be copied using the memcpy function, for example.)

[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. Unfortunately, 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).

[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.

C's primary use is for "system programming",

C's primary use is 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 has also been widely used to implement end-user applications, although as applications became larger much of that development shifted to other, higher-level languages.

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

C is used as an intermediate language by some implementations of higher-level languages, which translate the input language to C source code, perhaps along with other object representations. The C source code is compiled by a C compiler to produce object code. This approach may be used to gain portability (C compilers exist for nearly all platforms) or for convenience (it avoids having to develop machine-specific code generators). Some programming languages which use C this way are Eiffel, Esterel, Gambit, the Glasgow Haskell Compiler, Lisp dialects, Lush, Sather, Squeak, and Vala.

Unfortunately, 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--.


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.

Each source file contains declarations and function definitions. Function definitions, in turn, contain declarations and statements. Declarations either define new types using keywords such as struct, union, and enum, or assign types to and perhaps reserve storage for new variables, usually by writing the type followed by the variable name. Keywords such as char and int specify built-in types. Sections of code are enclosed in braces ({ and }) 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 operands to most operators, as well as the arguments to functions, 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. This permits a high degree of object code optimization by the compiler, but requires C programmers to exert more care to obtain reliable results than is needed for other programming languages.


C 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
equality testing
order relations
boolean logic
bitwise logic
assignment
increment and decrement
reference and dereference
conditional evaluation
member selection
type conversion
object size
function argument collection
sequencing
subexpression grouping

Operator precedence and associativity
What follows is the list of C operators sorted from highest to lowest priority (precedence). Operators of same priority are presented on the same line. (That the post-increment operator (++) has higher priority than the dereference operator (*) means that an expression *p++ is grouped as *(p++) and not (*p)++. That the subtraction operator (-) has left-to-right associativity means that an expression a-b-c is grouped as (a-b)-c and not a-(b-c).)

Class Associativity Operators
Grouping Nesting (expr)
Postfix Left-to-Right (args) [] -> . expr++ expr--
Unary Right-to-Left ! ~ + − * & (typecast) sizeof ++expr --expr
Multiplicative Left-to-Right * / %
Additive Left-to-Right + -
Shift Left-to-Right << >>
Relational Left-to-Right < <= > >=
Equality Left-to-Right == !=
Bitwise AND Left-to-Right &
Bitwise XOR Left-to-Right ^
Bitwise OR Left-to-Right
Logical AND Left-to-Right &&
Logical OR Left-to-Right
Conditional Right-to-Left ?:
Assignment Right-to-Left = += -= *= /= &= = ^= <<= >>=
Sequence Left-to-Right ,


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

main()
{
printf("hello, world\n");
}
The above program will compile on most modern compilers that are not in compliance mode, but does not meet the requirements of either C89 or C99. Compiling this program in C99 compliance mode will result in warning or error messages.[8] A compliant version of the above program follows:

#include

int main(void)
{
printf("hello, world\n");
return 0;
}
What follows is a line-by-line analysis of the above program:

#include
This first line of the program is a preprocessing directive, #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 file. The header file stdio.h contains declarations for standard input and output functions such as printf. The angle brackets surrounding stdio.h indicate that stdio.h can be found using an implementation-defined search strategy. Double quotes may also be used for headers, thus allowing the implementation to supply (up to) two strategies. Typically, angle brackets are reserved for headers supplied by the C compiler, and double quotes for local or installation-specific headers.

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

{
This opening curly brace indicates the beginning of the definition of the main function.

printf("hello, world\n");
This line calls (executes the code for) a function named printf, which is declared in the included header stdio.h and 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 the 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 by the caller. (A more careful program might test the return value to determine whether or not the printf function succeeded.) The semicolon ; terminates the statement.

return 0;
This line 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).

}
This closing curly brace indicates the end of the code for the main function.

TAKE A TOUR HERE ::-