3.2. Fundamental Data Types¶
3.2.1. Data Declarations¶
Declarations serve two purposes:
- They tell the compiler to set aside an appropriate amount of space in memory for the program’s data (variables).
- They enable the compiler to correctly operate on the variables. The
compiler needs to know the data type to correctly operate on a variable.
The compiler needs to know how many bytes are used by variables and the
format of the bits. The meaning of the binary bits of a variable are
different for different data types.
- char is 8 bit (1 byte) ASCII, but can also store numeric data.
- int is 4 byte 2’s complement.
- short is 2 byte 2’s complement.
- long is 8 byte 2’s complement.
- unsigned (int, short, and long) are straight binary
- float is 4 byte IEEE Floating Point Single Precision Standard.
- double is 8 byte IEEE Floating Point Double Precision Standard.
3.2.2. Character - integer relation¶
The ASCII code is a set of integer numbers used to represent characters.
char c = 'a'; /* 'a' has ASCII value 97 */ int i = 65; /* 65 is ASCII for 'A' */ printf( "%c", c + 1 ); /* b */ printf( "%d", c + 2 ); /* 99 */ printf( "%c", i + 3 ); /* D */
3.2.3. Integers¶
A variations of int (unsigned, long, …) are stored binary data which is directly translated to it’s base-10 value. See topic 1 notes for the ranges of the various integer data types.
3.2.4. Floating point data¶
Variables of type float and double are stored in three parts: the sign, the mantissa (normalized value), and an exponent.
3.2.5. sizeof¶
Because some variables take different amount of memory of different systems, C provides an operator which returns the number of bytes needed to store a given type of data.
i = sizeof(char); j = sizeof(long); k = sizeof(double);
The sizeof
operator is very useful when manually allocating
memory and dealing with complex data structures.
3.2.6. Conversions and Casts¶
Two mechanisms exist to convert data from one data type to another, implicit conversion and explicit conversion, which is also called casting.
3.2.6.1. implicit conversion¶
If a arithmetic operation on two variables of differing types is performed, one of the variables is converted or promoted to the same data as the other before the operation is performed. In general, smaller data types are always promoted to the larger data type.
3.2.6.2. explicit conversion or casts¶
The programmer can tell the compiler what types of conversions should be performed by using a cast. A cast is formed by putting a data type keyword in parenthesis in front of a variable name or expression.
x = (float)(m * j); i = (int)x + k;