|
|
|
|
Basic built-in types
The Standard C specification for built-in
types (which C++ inherits) doesn’t say how many bits each of the built-in
types must contain. Instead, it stipulates the minimum and maximum values that
the built-in type must be able to hold. When a machine is based on binary, this
maximum value can be directly translated into a minimum number of bits necessary
to hold that value. However, if a machine uses, for example, binary-coded
decimal (BCD) to represent numbers, then the amount of space in the machine
required to hold the maximum numbers for each data type will be different. The
minimum and maximum values that can be stored in the various data types are
defined in the system header files limits.h and
float.h (in C++ you will generally #include
<climits> and <cfloat> instead).
C and C++ have four basic built-in data
types, described here for binary-based machines. A
char is for character
storage and uses a minimum of 8 bits (one byte) of storage, although it may be
larger. An int stores an
integral number and uses a minimum of two bytes of storage. The
float and
double types store floating-point
numbers, usually in IEEE floating-point
format. float is for single-precision floating
point and double is for double-precision floating
point.
As mentioned previously, you can define
variables anywhere in a scope, and you can define and initialize
them at the same time.
Here’s how to define variables using the four basic data
types:
//: C03:Basic.cpp
// Defining the four basic data
// types in C and C++
int main() {
// Definition without initialization:
char protein;
int carbohydrates;
float fiber;
double fat;
// Simultaneous definition & initialization:
char pizza = 'A', pop = 'Z';
int dongdings = 100, twinkles = 150,
heehos = 200;
float chocolate = 3.14159;
// Exponential notation:
double fudge_ripple = 6e-4;
} ///:~
The first part of the program defines
variables of the four basic data types without initializing them. If you
don’t initialize a variable, the Standard says that its contents are
undefined (usually, this means they contain garbage). The second part of the
program defines and initializes variables at the same time (it’s always
best, if possible, to provide an initialization value at the point of
definition). Notice the use of exponential notation in
the constant 6e-4, meaning “6 times 10 to the minus fourth
power.”
|
|
|