Data declarations

Basic data types        Derived (composite) data types 
	int			arrays (including C strings)
	char 			structs
	float			classes (C++)
        bool                    pointers
        string

Data in a program can be constant (literal) or variable.
constant		variable
 5			int i;
 5.0			float f;
 '5'			char c;
 "5"			string s;

int

int a, b;   // "little boxes" can store one int value
int num;    // some part of memory of certain size
Size of int variable varies by machine: Size determines range of integer values.
old Turbo compilers: usually 2 bytes	-32768 thru +32767
Now: 4 bytes		~-2 billion thru ~+2 billion
Values outside the range don't exist in the computer.

Even with 4 byte int, this overflow problem exists.

int a, b;
a = 2000000000;
b = 1000000000;
cout << a+b;   // outputs -1294967296, ie. garbage but no error indication.
overflow.cpp Try it

Variations on int (useful for larger ranges)

short:	maybe smaller than int, e.g. 2 bytes.  (save memory)
long: 	on PC's is 4 bytes, so the 4 billion range, i.e. same as int.
unsigned:  positives	unsigned long int range: 0 thru ~4 billion
long long: 64-bit int
Run the sizes.cpp to see what the sizes of numeric types are.

float

Variation on float:

double 8 bytes; ~14 digits of accuracy; bigger range too. All real number constants in program are double.

All the number types can be freely mixed in expressions. The only questionable thing is to assign a float or double value to an int variable because it will be truncated (everything to the right of the decimal point is chopped off).

int i;
float f;
double d;
f = i * i;	//OK
f = i * f;	//OK
i = f + 1;	//i is int, only will store integer part of expression.  Avoid

/ is division operator. If both values are integers, will do integer division (whole number division) 7 / 2 == 3
One or both operands have to be real number for real division: 7.0 / 2 == 3.5
If have two ints and want to divide and get real result need to cast (convert) one or both to float:

int a, b;
a = 7;
b = 2;
cout << a / b << endl;          // 3 is output
cout << float(a) / b << endl;   // 3.5 is output
//value of a changed to float (a itself is still an int variable and its value is still int 7)



Output formatting:

#include <iomanip>    //at top with other includes.  to use the "set" manipulators.


//field width.  use that many positions for value (int, float, string)
cout << setw(5) << a << setw(4) << b << endl;

//endl manipulator Adds a newline and flushes output stream.

// real values:
cout << setprecision(2);   // no more than 2 digits after decimal point
		// applies to all floats in rest of program (or until another setprecision)

//to always output the . and the precision: do this "magic incantation"
cout << setiosflags(ios::fixed|ios::showpoint);
//OR
cout << fixed << showpoint;
// floats will be output xxx.yy      wxyz.dd      Useful for $$$.cents
Next (char)
©2000 David Wills