Chapter 1: Data Types, Variables, and Constants
C and C++ offer the programmer a rich
assortment of built-in data types. Programmer-defined data types can be created
to fit virtually any need. Variables can be created for any valid data type.
Also, it is possible to specify constants of C/C++’s built-in types. In this
section, various features relating to data types, variables, and constants are
discussed.
The Basic Types
C89 defines the following elemental data types:
Type
|
Keyword
|
---|---|
Character
|
char
|
Integer
|
int
|
Floating point
|
float
|
Double floating point
|
double
|
Valueless
|
void
|
To these, C99 adds the following:
Type
|
Keyword
|
---|---|
Boolean (true/false)
|
_Bool
|
Complex
|
_Complex
|
Imaginary
|
_Imaginary
|
C++ defines the following basic types:
Type
|
Keyword
|
---|---|
Boolean (true/false)
|
bool
|
Character
|
char
|
Integer
|
int
|
Floating point
|
float
|
Double floating point
|
double
|
Valueless
|
void
|
Wide character
|
wchar_t
|
Several of the basic types can be modified using one or more of
these type modifiers:
-
signed
-
unsigned
-
short
-
long
The type modifiers precede the type name that they modify. The
basic arithmetic types, including modifiers, allowed by C and C++ are shown in
the following table along with their guaranteed minimum ranges. Most compilers
will exceed the minimums for one or more types. Also, if your computer uses
two’s complement arithmetic (as most do), then the smallest negative value that
can be stored by a signed integer will be one more than the minimums shown. For
example, the range of an int for most computers is –32,768
to 32,767. Whether type char is signed or unsigned is
implementation dependent.
Type
|
Minimum Range
|
---|---|
char
|
–127 to 127 or 0 to 255
|
unsigned char
|
0 to 255
|
signed char
|
–127 to 127
|
int
|
–32,767 to 32,767
|
unsigned int
|
0 to 65,535
|
signed int
|
same as int
|
short int
|
same as int
|
unsigned short int
|
0 to 65,535
|
signed short int
|
same as short int
|
long int
|
–2,147,483,647 to 2,147,483,647
|
signed long int
|
same as long int
|
unsigned long int
|
0 to 4,294,967,295
|
long long int
|
–(263–1) to 263–1 (C99
only)
|
signed long long int
|
same as long long int (C99 only)
|
unsigned long long int
|
0 to 264–1 (C99 only)
|
float
|
6 digits of precision
|
double
|
10 digits of precision
|
long double
|
10 digits of precision
|
wchar_t
|
same as unsigned int
|
Declaring Variables
All variables must be declared prior to use. Here is the
general form of a declaration:
type variable_name;
For example, to declare x to be a float, y to be an integer, and ch to be a character, you would write
float x;int y;;char ch
You can declare more than one variable of a type by using a
comma-separated list. For example, the following statement declares three
integers:
int a, b, c;
Initializing Variables
A variable can be initialized by following its name with an
equal sign and an initial value. For example, this declaration assigns count an initial value of 100:
int count = 100;
An initializer can be any expression that is valid when the
variable is declared. This includes other variables and function calls. However,
in C, global variables and static local variables must be
initialized using only constant expressions.
Identifiers
Identifiers may be of any length. However, not all characters will
necessarily be significant. There are two types of identifiers: external and
internal. An external identifier will be involved in an external link process.
These identifiers, called external names, include function
names and global variable names that are shared between files. If the identifier
is not used in an external link process, it is internal. This type of identifier
is called an internal name and includes the names of local
variables, for example. In C89, at least the first 6 characters of an external
identifier and at least the first 31 characters of an internal identifier will
be significant. C99 has increased these values. In C99, an external identifier
has at least 31 significant characters and an internal identifier has at least
63 significant characters. In C++, at least the first 1,024 characters of an
identifier are significant.
The underscore is often used for clarity, such as first_time, or to begin a name, such as _count.
Uppercase and lowercase are different. For example, test and
TEST are two different variables. C/C++ reserves all
identifiers that begin with two underscores, or an underscore followed by an
uppercase letter.
Classes
The class is C++’s basic unit of
encapsulation. A class is defined using the class keyword.
Classes are not part of the C language. A class is essentially a collection of
variables and functions that manipulate those variables. The variables and
functions that form a class are called members. The
general form of class is shown here:
class class-name : inheritance-list {
// private members by default
protected:
// private members that can be inheritedpublic:// public members} object-list;
Here, class-name is the name of the class
type. Once the class declaration has been compiled, the class-name becomes a new type name that can be used to
declare objects of the class. The object-list is a
comma-separated list of objects of type class-name. This
list is optional. Class objects can be declared later in your program by simply
using the class name. The inheritance-list is also
optional. When present, it specifies the base class or classes that the new
class inherits. (See the following section entitled “Inheritance.”)
A class can include a constructor function
and a destructor function. (Either or both are optional.)
A constructor is called when an object of the class is first created. The
destructor is called when an object is destroyed. A constructor has the same
name as the class. A destructor has the same name as the class, but is preceded
by a ~ (tilde). Neither constructors nor destructors have
return types. In a class hierarchy, constructors are executed in order of
derivation and destructors are executed in reverse order.
By default, all elements of a class are private to that class and
can be accessed only by other members of that class. To allow an element of the
class to be accessed by functions that are not members of the class, you must
declare them after the keyword public. For example:
class myclass {int a, b; // private to myclasspublic:ss members accessible by nonmembersvoid// clasetab(int i, int j) { a = i; b = j; }<< endl; }} ;
ass ob1, ob2;myc lvoid showab() { cout << a << ' ' <<b
This declaration creates a class type, called myclass, that contains two private variables, a
and b. It also contains two public functions called setab( ) and showab( ). The fragment also
declares two objects of type myclass called ob1 and ob2.
To allow a member of a class to be inherited, but to otherwise be
private, specify it as protected. A protected member is
available to derived classes, but is unavailable outside its class
hierarchy.
When operating on an object of a class, use the dot (.) operator to reference individual members. The arrow operator
(–>) is used when accessing an object
through a pointer. For example, the following accesses the putinfo( ) function of ob using the dot
operator and the show( ) function using the arrow
operator:
struct cl_type {int x;;
public:floatf void putinfo(int a, float t) { x = a; f = t; }void show() { cout << a << ' ' << f << endl; }p} ;c // ...l_type ob, *p;ob.putinf) = &ob;o(10, 0.23
// put ob's address in pp->show();
// displays ob's data
Inheritanceanother, a class hierarchy is formed. The general form forIn C++, one class can inherit the characteristics of another. The inherited class is usually called the base class. The inheriting class is referred to as a derived class. When one class inherits
inheriting a class is
class class-name : accessbase-class-name {
// . . .
} ;is inherited, and it must be either private, public, or protected. (It can also be omitted,Here, access determines how the base class
in which case public is assumed if the derived class is a struct, or private if the derived class is a class.) To inherit more than one class, use a comma-separated
list.public and protected members of the baseIf access is public, all
class become public and protected members of
the derived class, respectively. If access is private, all public and protected members of the base class become private members of the derived class. If access is protected, all public and protected members of the base classbecome protected members of the derived class.In the following class hierarchy, derived inherits base as private. This means that i becomes a private member of derived.class base {public:};
lacint i;
ss derived : private base {int j;public:{ j = i = a; }
int getj() { rderived(int a)eturn j; }{ return i; } // OK, derived has access to iint geti( ) ob(9); // create a derived object
};ved
der i; // OKcout << ob.geti() << " " << ob.getj(
/ ob.i = 10; // ERROR, i is privat/)e to derived!
StructuresA structure is created using the keyword struct. In C++, a structure also defines a class. The only difference between class and struct is that, by default, all members of a structure are public. To make a member private, you must use the private keyword. The general form of a structure declaration is like this:struct struct-name : inheritance-list{/ public members by defaultp/rotected:// private members// private members
}private:that can be inheritedobject-list;In C, several restrictions apply to structures. First, they may contain only data members; member functions are not allowed. C structures do not support inheritance. Also, all members are public and the keywords public, protected, and private are not allowed.
UnionsA union is a class type in which all data members share the same memory location. In C++, a union may include both member functions and data. In a union, all of its ents, you must use the private keyword. The general form for declaration of members are public by default. To create private eleunion is aunion class-nameIn C, unions may contain only data members and the private keyword is not supported.The elements of a union overlay each other. For example,union tom
{ char ch;int x;} t;declares union tom, which looks like this in memory (assuming 2-byte integers):Like a class, the individual variables that comprise the union are referenced using the dot operator. The arrow operator is used with a pointer to a union.There are several restrictions that apply to unions. First, a union cannot inherit any other class of any type. A union cannot be a base class. A union cannot have virtual member functions. No members may be declaredas static. A reference member cannot be used. A union cannot have as a member= operator. Finally, no object any object that overloads the an be a member of a union if the object’s class explicitly defines a cconstructor or destructor function. (Objects that have only the default constructors and destructors are acceptable.) There is a special type of union in C++ called an anonymous union. An anonymous union declaration does not contain a class name and no objects of that union are declared. Instead, an anonymous union simply tells the compiler that its member variables are to share the same memory location. However, the variables w perator syntax. The variables that make up an anonymous union are at the themselves are referred to directly, without using the normal dot or arroe same scope level as any other variable declared within the same block. This implies scope. For example, here is an anonymous union: that the union variable names must not conflict with any other names valid within theirunion
{ // anonymous unionint a; // a and f sharefloat f; // the same memory location};// ...a= 10; // access acout << f; // access fsame memory location. As you can see, the names of the union variables areHere, a and f both share the
referred to directly without the use of the dot or arrow operator.All restrictions that apply to unions in general apply to anonymous unions. In addition, anonymous unions must contain only data—no member functions are allowed. Anonymous unions may not contain the private or protected keywords. Finally, an anonymous union with namespace scope must be declared as static.
C TagsIn C, the name of a structure, union, or enumeration does not define a complete type name. In C++, it does. For example, the following fragment is valid for C++, but not for C:struct s_type
{ int i;double d;};// ...// OK for C++, but not for Cs_type x;In C++, s_type defines a complete type name and can be used, by itself, to declare objects. In C, s_type defines a tag, which is not a complete type specifier. In C, you need to precede a tag name with either struct, union, or enum when declaring objects. For example,struct s_type x; // now OK for C
The preceding syntax is also permissible in C++, but seldom used.
ArraysYou may declare arrays of any data type, including classes.The general form of a singly dimensioned array istype var-name[size];where type specifies the data type of each element in the array and size specifies the number ofelements in the array. For example, to declare an integer array x of 100 elements, you would writeint x[100];
This will create an array that is 100 elements long with the firstelement being 0 and the last being 99. For example, the following loop will load
the numbers 0 through 99 into array x:for(t=0; t<100; t++) x[t] = t;
Multidimensional arrays are declared by placing the additionaldimensions inside additional brackets. For example, to declare a 10 × 20 integer
array, you would writeint x[10][20];
Arrays can be initialized by using a bracketed list ofinitializers. For example,
int count[5] = { 1, 2, 3, 4, 5 };In C89 and C++, array dimensions must be specified byconstant values. Thus, in C89 and C++, all array dimensions are fixed at compile time and cannot change over the lifetime of a program. However, in C99, the including those whose values are known only at compile time. This is called dimensions of a local array can be specified by any valid integer expression,a variable- length array. Thus, the dimensions of a variable-length array can differ each time its declaration statement is encountered.
Defining New Type Names Using typedefYou can create a new name for an existing type using typedef. Its general form istypedef type newname;For example, the following tells the compiler that feet is another name for int: typedef int feet;Now, the following declaration is perfectly legal and creates an integer variable called distance:feet distance;
ConstantsConstants, also called literals, refer to fixed values that cannot be altered by the program. Constants can be of any of the basic data types. The way each constant is represented depends upon its type. Character constants are enclosed between nstants are specified as numbers without fractional components. For example, single quotes. For example 'a' and '+' are both character constants. Integer co10 and –100 are integer constants. Floating-point constants require the use of123 is a floating-point constant. You may also use scientific notation for the decimal point followed by the number’s fractional component. For example,floating-point numbers.There are two floating-point types: float and double. Also, there are several flavors of the basic types thatare generated using the type modifiers. By default, the compiler fits a numeric constant into the smallest compatible data type that will hold it. The only assumed to be of type exceptions to the smallest-type rule are floating-point constants, which are double. For many programs, the compiler defaults are perfectly adequate. However, it is possible to specify precisely the type of constant you want. To specify the exact type of numeric constant, use a suffix. For floating-point types, if you follow the number with an F, the number is treated as a float. If you follow it with an L, the number becomes a long double. For integer types, the U suffix stands
Data Type Constant Examples int 1 123 21000 –234 long int 35000L –34L unsigned int 10000U 987U float 123.23F 4.34e–3F double 123.23 12312333 –0.9876324 long double 1001.2LC99 also allows you to specify a long long integer constant by specifying the suffix LL (or ll).
Hexadecimal and Octal ConstantsIt is sometimes easier to use a number system based on 8 or 16 instead of 10. The number system based on 8 is called octal and uses the digits 0 through 7. In octal, the number 10 is the same as 8 in decimal. The base 16 number system is called hexadecimal and uses the digits 0 through 9 plus the letters A through F, which stand for 10, 11, 12, 13, 14, and 15. For example, the hexadecimal number 10 is 16 in decimal. Because of the frequency with which these two number systems are used, C/C++ allows you to specify integer constants in hexadecimal or octal instead of decimal if you prefer. A hexadecimal constant hexadecimal form. An octal constant begins with a zero. Here are two examples must begin with a 0x (a zero followed by an x) or 0X, followed by the constant in:int hex = 0x80; // 128 in decimalint oct = 012; // 10 in decimal
String ConstantsC/C++ supports one other type of constant in addition to those of the predefined data types: a string. A string is a set of characters enclosed by double quotes. For example, "this is a test" is a string. You must not confuse strings with characters. A single-character containing only one letter. String constants are automatically null termina constant is enclosed by single quotes, such as 'a'. However, "a" is a stringted compiler. C++ also supports a string class,
Boolean ConstantsC99, which adds the _Bool type to C, does not specify any built-in Boolean constants. However, if your program includes the header <stdbool.h>, then the macros true and false are defined. Also, includingC++ specifies two Boolean constants: true and false.<stdbool.h> causes the macro bool tobe defined as another name for _Bool. Thus, it is possible tocreate code that is compatible with both C99 and C++. Remember, however, that C89 does not define a Boolean type.Complex ConstantsIn C99, if you include the header <complex.h>, then the following complex and imaginary constants are defined.
_Complex_I (const float _Complex) i _Imaginary_I (const float _Imaginary) i I _Imaginary_I (or _Complex_I if imaginary types are not supported)Here, i represents the imaginary value,which is the square root of –1.Backslash Character Constants
Enclosing character constants in single quotes works for most printing characters, but a few, such as the carriage return, are impossible to enter into your program’s source code from the backslash keyboard. For this reason, C/C++ recognizes several haracter constants, also called escape sequences. hese constants are listed here:
Code Meaning \b Backspace \f Form feed \n Newline \r Carriage return \t Horizontal tab \" Double quote \' Single quote \\ Backslash \v Vertical tab \a Alert \N Octal constant (where N is an octal constant) \xN Hexadecimal constant (where N is a hexadecimal constant) \? Question markexample, the following statement outputs a newline and a tab and then prints theThe backslash constants can be used anywhere a character can. For
string “This is a test”.cout << "\n\tThis is a test";
Goto Next Chapter..........
No comments:
Post a Comment