You can often use one type in place of another, e.g., logical value type is not provided in C, you can use character type to replace it: 0 means FALSE, non-zero means true.
Syntax | Name | use |
---|---|---|
char | character | Character or very short integer (-128..127) |
short | short integer | uses 2 byte memory, value between -32768 and 32767 |
int | ordinary integer | uses 4 byte memory, value between -2147483648 and 2147483647 |
long | long integer | uses 8 bytes memory, value between -9223372036854775808 and 9223372036854775807 |
float | single precision float | uses 4 byte memory, absolute value between 1.4E-45 and 3.4E38 |
double | double precision float | uses 8 byte memory, absolute value between 4.9E-324 and 1.8E308 |
float A, B, C; - Defines 3 float variables A = 4; B = 5; C = A + B; |
int A; - Defines integer float B, C; - Defines 2 float variables A = 4; B = 5; C = A + B; - value of A must be converted to FLOAT first !!! |
When you assign a value of a higher type to a variable of a lower type, you may NOT obtain a correct value !!!
Example:
int i; short s; i = 9827563; s = i; // <-- This conversion is // DANGEROUS !!! |
C++ will NOT allow this new type to operate with a float variable: click here
Save program and compile with "CC user-type1.C" - you will see error messages
C++ will now allow this new type to operate with a float variable: click here
Save program and compile with "CC user-type2.C" - you will NOT see error messages
Reason for using user-defined data types:
The most common computer application is NOT numerical analysis, but data management - billions of pieces of information are stored.
If you can represent the values by a smaller integer type, you save a lot of space (and can store more data)
In computation (especially heavy numerical math applications), operations on lower type values are faster.
Reason: higher datatypes use more bits in representation. It takes longer time to move the data around to be operated (need to move the value from memory to CPU and back in operations).
Example Programs: (shows difference in speed for float and double type)