answer 1

skillfulwolverineΛογισμικό & κατασκευή λογ/κού

2 Δεκ 2013 (πριν από 3 χρόνια και 9 μήνες)

190 εμφανίσεις



BCA


INTRODUCTION TO C++ PROGRAMMING

5MARK:

1.

Uses

of C++ programming

C is often used for "
system
programming
", including implementing
operating
systems

and
embedded system

applications, d
ue 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 im
posed data access
requirements, and low
run
-
time

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

Some reasons for choosing C over
interpreted languages

are its speed, stability, and near
-
universal availability.
[14]

One consequence of C's wide availability 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, whi
ch 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 completel
y 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 c
onvenience; 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++
,
COBOL
,
Eiffel
,
Gambit
,
GHC
,
Modula
-
3
,
Squeak
, and
Vala
.
[15]

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.


Syntax

C has a
formal grammar

specified by the C standard.
[16]

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 (since 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 spec
ify 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.

2.

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
subroutines
, which are called "functions" (although not in the
strict sense of
functional programming
). Function
parameters

are
always passed by
value. Pass
-
by
-
reference is simulated in C by explicitly passing
pointer

values. C
program source text is
free
-
format
, using the
semicolon

as a
statement

terminator
and curly braces for grouping blocks of statements.

The C language also exhibits the following more specific characteristics:



There are a small, fixed number of keywords, including a full set of
flow of
control

primitives:
for
,
if
,
while
,
switch
, and
do..while
. There is basically
one
namespace
, and user
-
defined names are not distinguished from
keywords by any

kind of
sigil
.



There are a large number of arithmetical and logical operators, such as +,
+=, ++, &, ~, etc.



More than one
assignment

may be performed in a single statement.



Function return values can be ignored when not needed.



Typing is
static
, but
weakly enforced
: all data has a type, but implicit
conversions can be performed; for instance, characters can be used as
integers.



Declaration

syntax

mimics usage context. C has no "define" keyw
ord;
instead, a statement beginning with the name of a type is taken as a
declaration. There is no "function" keyword; instead, a function is indicated
by the parentheses of an argument list.



User
-
defined (typedef) and compound types are possible.

o

Heterogeneous aggregate data types (
struct
) allow related data
elements to be accessed, for example assigned, as a unit.

o

Array

indexing is a secondary notion, defined in terms of pointer
arithmetic. Unlike structs, arrays are not first
-
class objects; they
cannot be assigned or compared using single built
-
in opera
tors. There
is no "array" keyword, in use or definition; instead, square brackets
indicate arrays syntactically, e.g. month[11].

o

Enumerated types

are possible with the enum k
eyword. They are not
tagged, and are freely interconvertible with integers.

o

Strings

are not a separate data type, but are conventionally
implemented a
s
null
-
terminated

arrays of characters.



Low
-
level access to
computer memory

is

possible by converting machine
addresses to typed
pointers
.



Procedures

(subroutines not returning values) are a special case of function,
with a dummy return type void.



Functions may not be defined within the lexical scope of other functions.



Function and data pointers permit
ad hoc

run
-
time polymorphism
.



A
preprocessor

performs
macro

definition,
source code

file inclusion, and
conditional compilation.



There is a basic form of
modularity
: files can be compiled separately and
linked

together, with control over which func
tions and data objects are
visible to other files via static and extern attributes.



Complex functionality such as
I/O
,
string

manipulation, and mathematical
functions are consistently delegated to
library routines
.

3.

VIRT
UAL MEMBER FUNCTIONS

Ordinarily, when a function in a derived class
overrides

a function in a base class,
the function to call is determined by the type of the object. A given function is
overridden when there exists no difference in the number or type of parameters
between two or more definitions of that function. Hence, at compil
e 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
[30]

allow t
he most specific implementation of the function to be called,
according to the actual run
-
time type of the object. In C++ implementations, 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 genera
l calls to virtual functions are resolved at run time.

In addition to standard member functions, operator overloads and destructors can
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, cannot be virtual.
Nonetheless a situation may arise where a copy of an object needs to be created
when a pointer to a derived object is p
assed as a pointer to a base object. In such a
case, a common solution is to create a
clone()

(or similar) virtual function that
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 parenthesis and before the semicolon. A class containing a pure virtual
function is called an
abstract data type
. Objects cannot be created from abstract
data types; they can only be derived from. Any derived class inherits the v
irtual
function as pure and must provide a non
-
pure definition of it (and all other pure
virtual functions) before objects of the derived class can be created. A program that
attempts to create an object of a class with a pure virtual member function or
in
herited pure virtual member function is ill
-
formed.

20MARK:

1.LANGUAGE FEATURES

C++ inherits most of
C's syntax
. The following is Bjarne Stroustrup's version of
the
Hello world program

that uses the
C++ Standard Library

stream facility t
o
write a message to
standard output
:
[23]
[24]

#include <iostream>



int main()

{


std::cout << "Hello, world!
\
n";

}

Within functions that define a non
-
void return type, failure to return a value before
control reaches the end of the function results in

undefined behaviour

(compilers
typically provide the means to issue a diagnostic in such a case).
[25]

The sole
exception to this rule is the main function, which implicitly returns a value of
zero.
[26]

Operators and operator overloading

C+
+ provides more than
35 operators
, covering basic arithmetic, bit manipulation,
indirection, comparisons, logical operations and others. Almost all operator
s can be
overloaded

for user
-
defined types, with a few notable exceptions such as member
access (. and .*) as well as the conditional operator. The rich set of
overloadable
operators is central to using C++ as a
domain
-
specific language
. The overloadable
operators are also an essential part of many advanced C++ pro
gramming
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
opera
nds that the operator uses (any operand may however be ignored by the
operator, though it will be evaluated prior to execution). Overloaded "&&" and "||"
operators lose their
short
-
circuit evaluation

property.

Operators that cannot be overloaded

Operator

Symbol

Scope resolution operator


::

Conditional operator


?:

Member selection operator


.*

"sizeof" operator


sizeof

"typeid" operator


typeid

T
emplates

C++ templates enable
generic programming
. C++ supports both function and class
templates. Templates may be parameterized by types, compile
-
time constants, and
other templates. C++ templates are implemented by
instantiation

at compile
-
time.
To instantiate a template, compilers substitute specific

arguments for a template's
parameters to generate a concrete function or class instance. Some substitutions are
not possible; these are eliminated by an overload resolution policy described by the
phrase "
Substitution failure is not an error
" (SFINAE). Templates are a powerful
tool that can be used for
generic programming
,
template metaprogramming
, and
code optimization, but this power implies a cost. Template use may increase code
size, since each
template instantiation produces a copy of the template code: one
for each set of template arguments. This is in contrast to run
-
time generics seen in
other languages (e.g.
Java
) where at compile
-
time the type is erased and a single
template body is preserved.

Templates are different from macros: while both of these compile
-
time language
features enable conditional compilation, templates are not restricted to lexical
substitu
tion. Templates are aware 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 par
ameters. 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/exc
lusion. 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
.

In addition, templates are a compile time me
chanism in C++ that 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, a template is a compile
-
time parameterized function or class written
without knowledge of the specific arguments used to instantiate it. Aft
er
instantiation, the resulting code is equivalent to code written specifically for the
passed arguments. In this manner, templates provide a way to decouple generic,
broadly applicable aspects of functions and classes (encoded in templates) from
specific
aspects (encoded in template parameters) without sacrificing performance
due to abstraction.

Objects

C++ classes

C++ introduces
object
-
oriented programming

(OOP) features to C. It offers
classes
, which provide the four features commonly present in OOP (and some non
-
OOP) languages:
abstraction
,
encapsulation
,
inheritance
, and
polymorphism
.
Objects are instances of classes created at runtime. One distinguishing feature of
C++ classes compared to classes in other programming languages is support for
deterministic
destructors
, which in turn provide support for the
Resource
Acquisition is Initialization

concept.

Encapsulation

Encapsulation

is the hiding of information in order to
ensure that data structures
and operators are used as intended and to make the usage model more obvious to
the developer. C++ provides the ability to define classes and functions as its
primary encapsulation mechanisms. Within a class, members can be decla
red as
either public, protected, or private in order to explicitly enforce encapsulation. 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
class
es 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.

Inheritance

Inheritance

allows one data type to acquire properties of other data types.
Inheritance from a
base class

may be d
eclared 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 "inher
itance". The other two forms are
much less frequently used. If the access specifier is omitted, a "class" inherits
privately, while a "struct" inherits publicly. 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.

Polymorphism

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
)
polymorphisms
. Compile
-
time polymorphism does not allow for certain run
-
time
decisions, while run
-
time polymorphism typically incurs a performance penalty.

Static polymorphism

Function overloading

allows programs to declare multiple functions having the
same name (but with different arguments). The functions are distinguished by the
number 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 dis
tinguish overloaded functions and would
result in a compile
-
time error message.

2.DATA TYPES

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 ch
ecks 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 data object in
some other way.

Pointers

C supports the use of
pointers
, a type of
reference

that records the address or
location of an object or function in memory. Pointers can be
dereferenced

to access
data stored at the addre
ss pointed to, or to invoke a pointed
-
to function. Pointers
can be manipulated using assignment or
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 automaticall
y 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

is performed using
pointers. Many data types, such as
trees
, are commonly implemented as
dynamic
ally allocated struct objects linked together using pointers. Pointers to
functions are useful for passing functions as arguments to
higher
-
order functions

(such
as
qsort

or
bsearch
) or as
callbacks

to be invoked by event handlers.

A
null pointer

value

explicitly points to no valid location. Dereferencing a null
pointer value is undefined, often resulting in

a
segmentation fault
. Null pointer
values 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
appropriate contexts in source code, such as for assigning to a pointer variable, a
null pointer constant

can be written as 0, with or withou
t explicit casting to a
pointer type, or as the NULL macro defined by several standard headers. In
conditional contexts, null pointer values evaluate to false, while all other pointer
values evaluate to true.

Void pointers (void *) point to objects of unsp
ecified 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 con
texts 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 undesirab
le 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 pr
ovide options for various levels of
checking. Some other programming languages address these problems by using
more restrictive
reference

types.

A
rrays

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.)
How
ever, 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 declared arrays and these
dynamic
ally 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 some compilers 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.

C does not have a special provision for declaring multidimensional arrays, but
rather relies on recursion withi
n 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 can
not 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 array
s.

C string

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

Fur
thermore, 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].

A demonstration of the interchangeability of p
ointers 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 pointe
r (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 contents may be copied, how
ever, by using the memcpy
function, or by accessing the individual elements.)

3.
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 allo
cation
: space for the object is provided in the binary at
compile
-
time; these objects have an
extent

(or lifetime) as long as the bina
ry
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
realloc

or
free

These three approaches are appropriate in different situations and have various
tradeoffs. For example, static memory allocation has little allocation overhead,
automatic
allocation may involve slightly more overhead, and dynamic memory
allocation can potentially have a great deal of overhead for both allocation and
deallocation. The persistent nature of static objects is useful for maintaining state
information across func
tion calls, automatic allocation is easy to use but stack
space is typically much more limited and transient than either static memory or
heap space, and dynamic memory allocation allows convenient 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 simplest because the
storage is managed by the compiler, freeing the programmer of the potentially
error
-
prone chore of manually allocating and rel
easing storage. However, many
data structures can change in size at runtime, and since static allocations (and
automatic allocations before C99) must have a fixed size at compile
-
time, there are
many situations in which dynamic allocation is necessary. Pri
or to the C99
standard, variable
-
sized arrays were a common example of this. (See the article on
malloc

for an example of dynamically allocated arrays.) Unlike automatic
allocation, which can
fail at run time with uncontrolled consequences, the dynamic
allocation functions return an indication (in the form of a null pointer value) when
the required storage cannot be allocated. (Static allocation that is too large is
usually detected by the
linker

or
loader
, before the program can even begin
execution.)

Unless other
wise specified, static objects contain zero or null pointer values upon
program startup. Automatically and dynamically allocated objects are initialized
only if an initial value is explicitly specified; otherwise they initially have
indeterminate values (t
ypically, 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

can occur.

Another issue is that heap memory allocation has to be 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()

is 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 for memory to be freed but continue to be
referenced, leading to unpredictable results. 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
.)

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 prot
otypes 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” C implementations, which target
embedded systems
, may provide
only a subset of the stan
dard library.) This library supports stream input and
output, memory allocation, mathematics, character strings, and time values.
Several separate standard headers (for example, stdio.h) specify the interfaces for
these and other standard library facilitie
s.

Another common set of C library functions are those used by applications
specifically targeted for
Unix

and
Unix
-
like

syste
ms, 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 othe
r
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
.

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 st
atements
that are not a good practice because they are 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 compi
lers 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 actions that are not a standard part of C, such as array bounds
c
hecking,
buffer overflow

detection,
serialization
, and
automatic garbage
collection
.

Tools such as
Purify

or
Valgrind

and linking with libraries containing special
versions of the
memory allocation functions

can help uncover runtime errors in
memory usage.

Related languages

C has directly or indirectly influenced many later languages such as
C#
,
D
,
Go
,
Java
,
JavaScript
,
Limbo
,
LPC
,
Perl
,
PHP
,
Python
, and Unix's
C Shell
. The most
pervasive influence has been syntactical: all of the languages mentioned comb
ine
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.

Several C or near
-
C interpreters exist, including
Ch

and
CINT
, which can also be
used for scripting.

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

fu
nctionality with C
-
like syntax. C++ adds
greater typing strength, scoping, and other tools useful in object
-
oriented
programming and permits
generic programming

via t
emplates. Nearly a superset of
C, C++ now supports most of C, with a few exceptions (see
Compatibility of C and
C++
).

Objective
-
C

was originally a very "thin" layer on top of C, and remains a strict
superset of C that permits object
-
oriented programming using a hybrid
dynamic/static typing paradigm. Objective
-
C derives its synta
x 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.

In addition to
C++

and
Objective
-
C
,
Ch
,
Cilk

and
Unified Parallel C

are nearly
super
sets of C.

4.
ARITHMETIC OPERATIONS

The basic arithmetic operations are addition, subtraction, multiplication and
division, although this subject also includes more advanced operations, such as
manipulations of
percentages
,
square roots
,
expon
entiation
, and
logarithmic
functions
. Arithmetic is performed according to an
order of operation
s
. Any set of
objects upon which all four arithmetic operations (except division by zero) can be
performed, and where these four operations obey the usual laws, is called a
field
.

A
ddition (+)

Addition

Addition is the basic operation of arithmetic. In its simplest form, addition
combines two numbers, the
addends

or
terms
, into a single number, the
sum

of the
numbers.

Adding more than two numbers can be viewed as repeated addition; this procedure
is known as
summation

and includes ways to add infinitely many numbers in an
infinite series
; repeated addition of the numb
er
one

is the most basic form of
counting
.

Addition is
commutative

and
associative

so the order the terms are added in does
not matter. The
identity element

of addition (the
additive identity
) is 0, that is,
adding zero to any number yields that same
number. Also, the
inverse element

of
addition (the
additive inverse
) is the opposite of an
y number, that is, adding the
opposite of any number to the number itself yields the additive identity,

0. For
example, the opposite of 7 is −7, so 7 + (−7) = 0.

Addition can be given geometrically as in the following example:

If we have two sticks of leng
ths
2

and
5
, then if we place the sticks one after
the other, the length of the stick thus formed is
2

+
5

=
7
.

Subtraction (−)

Subtraction is the opposite of addition. Subtraction finds the
difference

between
two numbers, the
minuend

minus the
subtrahend
.

If the minuend is larger than the
subtrahend, the difference is positive; if the minuend is smaller than the
subtrahend, the difference is negative; if they are equal, the difference is zero.

Subtraction is neither commutative nor associative. For that re
ason, it is often
helpful to look at subtraction as addition of the minuend and the opposite of the
subtrahend, that is
a


b

=
a

+ (−
b
). When written as a sum, all the properties of
addition hold.

There are several methods for calculating results, some of

which are particularly
advantageous to machine calculation. For example, digital computers employ the
method of
two's complement
. Of great importance is the counting up
method by
which change is made. Suppose an amount
P

is given to pay the required amount
Q
, with
P

greater than
Q
. Rather than performing the subtraction
P


Q

and
counting out that amount in change, money is counted out starting at
Q

and
continuing until reaching
P
. Although the amount counted out must equal the result
of the subtraction
P


Q
, the subtraction was never really done and the value of
P


Q

might still be unknown to the change
-
maker.

Multiplication (× or ∙ or *)

Multipli
cation is the second basic operation of arithmetic. Multiplication also
combines two numbers into a single number, the
product
. The two original
numbers are called the
multiplier

and the
multiplicand
, sometimes both simply
called
factors
.

Multiplication is

best viewed as a scaling operation. If the numbers are imagined as
lying in a line, multiplication by a number, say
, greater than 1 is the same as
stretching everything away from zero uniformly, in such a way that the number 1
itself is stretched to whe
re
was. Similarly, multiplying by a number less than 1
can be imagined as squeezing towards zero. (Again, in such a way that 1 goes to
the multiplicand.)

Multiplication is commutative and associative; further it is
distributive

over
addition and subtraction. The
multiplicative identity

is 1, that is, multiplying any
number by 1 yie
lds that same number. Also, the
multiplicative inverse

is the
reciprocal

of any number (except zero; zero is the only number without a
multiplicative inverse), that is, multiplying the reciprocal of any number by the
number itself yields the multiplicative identity.

The product of
a

and
b

is written as
a

×

b

or

a



b
. When
a

or
b

are expressions not
written simply with digits, it is also written by simple juxtaposition:

ab
. In
computer programming languages and software packages in which one can only
use characters normally found on a keyboard, it is often
written with an
asterisk:

a

*

b
.

Division (÷ or /)

Division is essentially the opposite of multiplication. Division finds the
quotient

of
two numbers, the
dividend

divided by the
divisor
. Any dividend
divided by zero

is
undefined. For positive numbers, if the dividend is larger than the divisor, the
quotient is greater than one, otherwise it is less than one (a similar rule applies for
negative numbers). The quotient multipl
ied by the divisor always yields the
dividend.

Division is neither commutative nor associative. As it is helpful to look at
subtraction as addition, it is helpful to look at division as multiplication of the
dividend times the
reciprocal

of the divisor, that is
a

÷

b

=

a

×

1
/
b
. When written as
a product, it obeys all the properties of multiplication.

Decimal arithmetic

Decimal representation

refers exclusively, in common use, to the written
numeral
system

employing
arabic numerals

as the
digits

for a
radix

10 ("decimal)
"
positional notation
; however, any
numeral system

based on powers of ten, e.g.,
Greek
,
Cyrillic
,
roman
, or
Chinese

numerals

may conceptually be described as
"decimal notation" or "decimal representation".

Modern methods for four fundamental operations (addition, subtraction.
multiplication and division) were first devised by
Brahmagupta

of India. This was
known during medieval Europe as "Modus Indoram" or Method of the Indians.
Positional notation (also known as "place
-
value notation") refers to the
representati
on or encoding of
numbers

using the same symbol for the different
orders of magnitude

(e.g., the "ones

place", "tens place", "hundreds place") and,
with a
radix point
, using those same symbols to represent
fractions

(e.g., the
"tenths place", “hundredths place"). For example, 507.36 denotes 5 hundreds (10
2
),
plus 0 tens (10
1
), plus 7 units (10
0
), plus 3 tenths (10
−1
) plus 6 hundredths (10
−2
).

Zero

as a number comparable to the other basic digits is a concept that is essential
to this notation, as is the concept of zero’s use as a placeholder, and as is the
definition of multiplication an
d addition with zero. The use of zero as a
placeholder and, therefore, the use of a positional notation is first attested to in the
Jain

text from
India

entitled the
Lokavibhâga
, dated 458 AD and it was only in the
early 13th century that these concepts, transmitted via the
scholarship of the Arabic
world
, were introduced into
Europe

by
Fibonacci
[3]

using the
Hindu
-
Arabic
numeral syste
m
.

Algorism

comprises all of the rules for performing arithmetic computations using
this type of written numeral. For example, addition produces the sum of two
arbitrary numbers. The resul
t is calculated by the repeated addition of single digits
from each number that occupies the same position, proceeding from right to left.
An addition table with ten rows and ten columns displays all possible values for
each sum. If an individual sum excee
ds the value nine, the result is represented
with two digits. The rightmost digit is the value for the current position, and the
result for the subsequent addition of the digits to the left increases by the value of
the second (leftmost) digit, which is al
ways one. This adjustment is termed a
carry

of the value one.

The process for multiplying two arbitrary numbers is similar to the process for
addition. A multiplication table with ten rows and ten columns lists the results for
each pair of digits. If an in
dividual product of a pair of digits exceeds nine, the
carry

adjustment increases the result of any subsequent multiplication from digits
to the left by a value equal to the second (leftmost) digit, which is any value from
one to eight (9

×

9

=

81). Additi
onal steps define the final result.

Similar techniques exist for subtraction and division.

The creation of a correct process for multiplication relies on the relationship
between values of adjacent digits. The value for any single digit in a numeral
depend
s on its position. Also, each position to the left represents a value ten times
larger than the position to the right. In mathematical terms, the
exponent

for the
radix

(base) of ten increases by one (to the left) or decreases by one (to the right).
Therefore, the value for any arbitrary digit is multiplied by a value of the form 10
n

with
integer

n
. The list of values corresponding to all possible positions for a single
digit is written as

{...,

10
2
,

10,

1,

10
−1
,

10
−2
,

...}.

Repeated multiplication of any value in this list by ten produces another value
in
the list. In mathematical terminology, this characteristic is defined as
closure
, and
the previous list is described as
closed under multiplication
. It is
the basis for
correctly finding the results of multiplication using the previous technique. This
outcome is one example of the uses of
number theory
.