Primitives
There are only four basic data types in C. The problems come later when custom
data types and compound data types come into use.
The primitives illustrate the history of C programming - current
CPU's are 32bit and the next generation are 64bit. Programs that use a lot of
single character variables, (char
type), may actually run slower on
64bit machines because 56bits of the CPU register are unused, wasting cache
space. However, CPU design does take this into account and you should not use
this as an excuse to waste memory on variables that use larger types than are
remotely necessary. (char[]
strings are not a problem.)
Modifiers
As mentioned, unsigned
can be used to make better use of the space
available. long
can also be used to create a 4byte integer without
the burden of the floating point. When combined, an unsigned long int has a
range from 0 to over 5million. These are called modifiers and allow the compiler
to allocate enough memory for these enlarged types from the beginning of the
program. One final modifier is const
- any primitive or modified
primitive can be deemed const
. A const value can only be assigned
at definition. Any attempt to change a const value later in the program will
generate a compiler error. This compares with the #define
macro
which must be pre-defined before the program is compiled - const allows you to
calculate a runtime value and define a new const to store it.
casts
Sometimes, you have a value in a floating point that needs to be passed to a
function that only accepts integers. Care is needed here because if you try to
convert from a large float to a smaller type, the final value is unpredictable.
Your code should check that the float value is LESS than the upper limit of the
smaller type before attempting the cast. Another problem is lack of
rounding - casting a float of 9.99 results in an integer value of 9, not 10.
Remember that the compiler will sometimes cast your variables implicitly by
casting the final result to the larger type. This ensures you don't lose data
but can cause confusion. Multiplying an integer by a double will result in a
double. If you need to force a cast from a larger type to a smaller type and
you've checked the size of the larger value, use the syntax:
myint = int(mydouble);
Some complex types
typedef unsigned int UINT
creates a type called UINT that is
exactly equivalent to an unsigned int defined in any other way.
const
and long
modifiers can also be used in a typedef
definition. sizeof(mystruct)
always
returns a consistent size.
struct ADDRESS {
int housenum;
char firstline[];
char postcode[];
};
ADDRESS home;
home.housenum = 56;
home.postcode = "W1 1AA";
This is part of www.codehelp.co.uk Copyright © 1998-2004 Neil
Williams
See the file about.html for
copying conditions.