Chapter6 Basic Data Type
Chapter6 Basic Data Type
com
Data Handling
Some commonly used data types are summarized in table along with
description.
Type Description
The exact sizes and ranges of values for the fundamental types are
implementation dependent. The header files <climits> (for the integral types)
and <cfloat> (for the floating-point types) specify the ranges of values
supported on your system.
int main ()
{
string mystring = "This is a string";
cout << mystring;
return 0;
}
Variable Initialization
Variable is a location in the computer memory which can store data and is given
a symbolic name for easy reference. The variables can be used to hold different
values at different times during the execution of a program.
Declaration of a variable
Before a variable is used in a program, we must declare it. This activity enables
the compiler to make available the appropriate type of location in the memory.
float total;
You can declare more than one variable of same type in a single single
statement
int x, y;
Initialization of variable
Constants
A variable which does not change its value during execution of a program is
known as a constant variable. Any attempt to change the value of a constant
will result in an error message. A constant in C++ can be of any of the basic
data types, const qualifier can be used to declare constant as shown below:
const float PI = 3.1415;
The above declaration means that PI is a constant of float types having a value
3.1415.
Examples of valid constant declarations are:
const int RATE = 50;
const float PI = 3.1415;
const char CH = 'A';
Type Conversion
The process in which one pre-defined type of expression is converted into
another type is called conversion. There are two types of conversion in C++.
1. Implicit conversion
2. Explicit conversion
Implicit conversion
Data type can be mixed in the expression. For example
double a;
int b = 5;
float c = 8.5;
a = b * c;
When two operands of different type are encountered in the same expression,
the lower type variable is converted to the higher type variable. The following
table shows the order of data types.
order
Data type
long double
(highest)
double
float
long To
int
char (lowest)
The int value of b is converted to type float and stored in a temporary variable
before being multiplied by the float variable c. The result is then converted to
double so that it can be assigned to the double variable a.
Explicit conversion
It is also called type casting. It temporarily changes a variable data type from
its declared data type to a new one. It may be noted here that type casting can
only be done on the right hand side the assignment statement.
totalPay = static_cast<double>(salary) + bonus;
Initially variable salary is defined as float but for the above calculation it is
first converted to double data type and then added to the variable bonus.