Get Adobe Flash player

The C++ Built-In Data Type and Arrays



 

The C++ Built-In Data Type

C++ provides built-in support for primitive arithmetic data types such as integer:

//declares an integer object, ival
//initialized to a first value of 1024
int ival = 1024;

It also supports double precision and single precision floating point data types:

//declares a double precision floating point object, dval
//initialized to a first value of 3.14159
double dval = 3.14159

//declares a single precision floating point object, fval
float fval = 3.14159

C++ also supports a Boolean data type as well as charcter type to hold individual elements of the character set.

The arithmetic data types provide built-in support for assignment and for the usual arithmetic operations, such as addition, subtraction, multiplication, and division, as well as relational operations, such as equality, inequality, greater than, less than and so on.

Example:

int ival2 = ival + 4096; //addition
int ival3 = ival2 – ival //subtraction

dval = fval * ival; //multiplication
ival = ival3 / 2; //division

bool result = ival2 == ival3; //equality
result = ival2 + ival != ival3; //inequality
result = fval + ival2 < result =” fval”> ival2; //greater-than

In addition, the standard library provides support for a collection of basic class abstractions, such as strings and complex number.

Array

An array is an ordered container of elements of a single type. For example, the sequence :
0 1 1 2 3 5 8 13 21
represent the first nine elements of the Fibonacci sequence. (Given the first two elements each subsequent element is generated by adding together the previous two).
To define and initialize an array to hold these elements, we write:
int fibon [9] = {0, 1 , 1, 2, 3, 5, 8, 13, 21};
The name of the array object is fibbon. It is an integer array with a dimension of nine elements. The first element is 0, and the last element is 21. We access the elements by indexing into the array using the subscript operator. For example, to read the first element, we might write:
int first_elem = fibon[1]; //not quite right
Unfortunately, this is incorrect, although it is not itself a language error.
One unintuitive aspect of array subscripting under C++ is that the element positions begin at 0 and not 1. The element at position 1 is really the second element. Similarly, the element at position 0 is really the first element. To access the last element of an array, we always index the dimension -1 element.
fibon[0]; //first element
fibon[1]; //second element
fibon[8]; //last element
fibon[9]; //oopss…
The element indexed by 9 is not an element of the array. The nine elements of fibon are indexed at position 0-8. A common beginner error is to instead index positions 1-9. It’s so common, in fact, that it has its own name: the off-by-one error.
Typically, we step through the elements of an array using a for loop. For example, the following program initializes an array of ten elements to the values 0 through 9 and then prints them in descending order to standard output:
int main()
{
int ia[10];
int index;
for (index=0; index <> 

// ia[0] = 0, ia[1] = 1, and so on
ia[index] = index;
for (index=9; index >= 0; –index)
cout <<> 

cout <<> 

}
Both loops iterate ten times. The three statements in parentheses following the keyword for do all the control work of the loop. The first statement assigns 0 to index:
index=0
It is executed once before the actual work of the loop begins. the second statement:
index <> 

represents the stoping condition of the loop. It begins the actual loop sequence. If it evaluates to tru, the statement (or statements) associated with the for loop are executed; if it evaluates to false, the loop terminates. In our example, each time that index evaluates to a value less than 10, the statement:
ia[index] = index;
is executed. The third statement:
++index
is shorthand notation for incrementing an arithmetic object by 1. It is equivalent to
index = index + 1;
It is executed after the statement associated with the for loop (assignment of the element subscripted by index with the value of index). Its execution completes one iteration of the for loop. The sequence repeats itself by once again testing the condition. When the condition evaluates to false, the loop terminates. The second loop operates in reverse order in printing the values.
Although C++ provides built-in support for an array type, that support is limited to the mechanics required to read and write individual elements. C++ does not support the abstraction of an array; there is no support for the operations one might wish to perform on an array, such as the assignment of one array to another, the comparison of two arrays for equality, or askingan array its size. Given two arrays, we cannot, for example, copy one to another as a unit using the assignment operator:
int array0[10], array1[10];
//error: cannot directly assign one array to another
array0 = array1
if we wish to assign one array to another, we must program that ourselves, copying each element in turn:
for (int index=0; index <> 

array0[index] = array1[index];
Moreover, the array type has no self-knowledge. As we said , it does not know its size, so we must keep track of that independently of the array itself.
This becomes troublesome when we wish to pass arrays as general arguments to functions. In C++, we say that an array, unlike the integer and floating points types, is not a first-class citizen of the language. It is inherited from the C language and reflects the separation of data and the algorithms that operate on that data that are characteristic of the procedure paradigm.

Dynamic Memory Allocation and Pointers


Under C++, objects can be allocated either statically-that is, by the compiler as it processes our program source code-or dynamically-that is, by the compiler as it processes ourprogram source code – or dynamically – that is, by a run-time library invoked during program execution. the promary trade-off between the two methods of memory allocation is efficiency versus flexibility: static memory allocation is considerably more efficient to allocate because it is done prior to the execution of the program the amout and type of memory that we need. We cannot, for example, easily process and store the words of an arbitrary text file using a statically allocated string array. In general, the storage of an unknown number of elements requires the flexibility of dynamic memory allocation.
Until now, all our memory allocation has been static. For example, the definition:
int ival = 1024;
instructs the compiler to allocate sufficient storage to hold any value of type int, associate the name ival with that storage, and then place an initial value of 1024 in that storage. This is all done prior to program execution.
There are two values associated with the object ival: the value it contains – in this case – 1024 – and the address at which that value is stored. In C++, it is possible to access either value. When we write:
int ival2 = ival + 1;
we are accessing the value that ival contains, adding 1 to it, and initializing ival2 with that new value. In our example, ival2 has an initial value of 1025. How do we access and store the memory address?
C++ supports a pointer type to hold the memory address values of objects. For example, to declare a pointer type capable of holding ival’s address value, we write:
// a pointer to an object to type int
int *pint;
C++ predefines a special address-of operator (&) that, when applied to an object, return that object;s address value. Thus, to assign pint to ival’s memory address, we write:
int *pint;
pint = &ival; //assign pint address of ival
To access the actual object pint addresses, we must first dereference pint using the dereference operator (*). For example, here is how we would indirectly add 1 to ival through pint:
//inderectly adding 1 to ival through pint
*pint = *pint + 1;
This is exactly equivalent to the following direct manipulation of ival:
//directly adding 1 to ival
ival = ival + 1;
In this example, there is no real benefit in using the indirect pointer manipulation of ival: it is bot less efficient and more easily misporgrammed that the direct manipuation of ival. It is presented to provide a simple first look at pointers. One of the primary uses of pointers in C++ is the management and manipulation of dynamically allocated memory.

2 Primary Differences Between Static and Dynamic Memory Allocation


1. Static objects are named variables that we manipulate directly, whereas dynamic objects are unnamed varaibles we manipulate indirectly through pointers.
2. The allocation and deallocation of static objects is handled automatically by the compiler; the programmer needs to understant it by need not do anything about it. The allocation and deallocation of dynamic objecs, in contrast, must be managed explicitly by the programmer and, in practice, is considerable more error-prone. It is accomplished through the use of the new and delete expressions.
Objects are allocated dynamically through one of two versions of the new expression. The first instance allocates a single object of a specific type:
int *pint = new int(1024);
allocates an unnamed object of type int, initializes that object to a first value of 1024 and then returns the address of the object in memory. The address is then used to initialize our pointer object, pint. For dynamically allocated memory, our only access is an indirect access through a pointer.
A second version of the new expression allocates an array of elements of a specified type and dimension:
int *pia = new int[4];
allocates an array of four integer elements. Unfortunately, there is no way to specify an explicit initial value for the individual elements of a dynamically allocated array.
A sometimes confusing aspect of allocating a dynamic array is that the value returned is simply a pointer, the same type that is returned for the allocation of a single dynamic object. For example, the difference between pint and pia is that pia holds the address of the first element of the four-element array, whereas pint simply holds the address of the single object.
Deallocate memory using one of two delete expression:
//delete a single object
delete pint;
//delete  an array of objects
delete [] pia;
If we forget to delete our dynamically allocated memory, we end up with a memory leak.
A memory leak is a chunk of dynamically allocated memory that we no longer have a pointer to, and thus we cannot return it to the program for later resure.
Source: C++ Primer by Lippman & Lajoie
---------------------------------------------------------------------------------------------------------------------------------------
If you find this page useful give it a
---------------------------------------------------------------------------------------------------------------------------------------

One Response to The C++ Built-In Data Type and Arrays

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

intichat banner

Featured Posts


 

My Mobile Site

QR Code - scan to visit our mobile site

This is a 2D-barcode containing the address of our mobile site.If your mobile has a barcode reader, simply snap this bar code with the camera and launch the site.

Say something:

  • Hello sainyo
    email
    hello
    17 May 2012
  • Biscotti
    email
    Interested in loading business? Check this out. May extra load ka na, makapagbenta ka pa.
    11 May 2012
  • Life is Fun!
    email
    Life is Fun!
    27 April 2012
  • adrian lucernas
    email
    pa link pls..
    14 April 2012
  • Pinoylivestream
    email
    Guys visit nio naman ang site ko .. http://www.pinoylivestream.info
    12 March 2012
  • oneitensei
    email
    wew... nakakaantok nmn puro busy.. busy busy.. ninanakaw pa ung load q.. di nmn aq narequest nagpapdla ang smart ng ringtones ubos load q.. ewwww
    1 March 2012
  • sin
    email
    pwd ba roaming sim unlimited?
    24 February 2012
  • amy
    email
    waaa.. earthquake!
    6 February 2012
  • oyeng
    email
    wata fuck smart!!!!
    5 February 2012
  • yea
    email
    ewan ko bah, alam nyo mga company,mayayaman na kayo dahil sa mga subscribers,kaya sana naman eh maging fair kayo.. oo tama unlicall 25 pesos lang,pero kunsumisyon bago maga register., dahil iyon sa pag iipit nyo.,para gamitin nalang ang regular load namin, tama? buti pa reg. load ang BILIS!., pero ang bilis din ng load namin maubos!! make any sense?
    31 January 2012
Your Shout
weekly trend micro give aways