If you like my posts please leave a comment.

Monday, July 23, 2012

C++: Data Types, Variables, Constants


Variables:

A variable is a named storage location which can store value of a particular data type; which can further change during the program execution. Each variable needs to be identified by an identifier and should be preceded with a valid C++ data type. There are some rules for naming an identifier in C++.
  1. A valid identifier is a sequence of one or more letters (a to z or A to Z), digits (0 to 9) or underscore ‘_’ characters. Remember, Spaces, punctuation marks or symbols cannot be used.
  2. Variable identifier should begin with an alphabet only. However digits can follow after the use of an alphabet. Note: Variable name can also start with an underscore ‘_’ but in some cases these may be reserved for compiler-specific keywords.
  3. Uppercase and lowercase letters are distinct. Example – int NUM and int num are not same.
  4. Identifiers must not mach any C++ keyword.
Beside the above rules mentioned; it is a good programming habit to keep the following points in mind
    • Always give a meaningful name to a variable, function etc.
Example: Suppose you want to store 9.50 as price of something then instead of writing
float p = 9.50 you can write float price = 9.50.
    • In case of lengthy identifiers use capital letters or underscores to separate the words.
Example: PaybleAmount or payble_amount
    • Use comments where it is necessary to describe the nature of the variable or function used.
    • Follow the indention for the pair of opening and closing braces while writing a program.
Here is the list of some of the keywords used in C / C++ language. You will come to known about most of these mentioned keywords in these two years.
asum, auto, break, case, catch, char, class, const, continue, default, delete, do, double, else, enum, extern, float, for, friend, goto, if, inline, int, long, new, operator, private, protected, public, register, return, short, signed, sizeof(), static, struct, switch, template, this, throw, try, typedef, union, unsigned, virtual void, violatile, while.

C++ Data Types:

As in the previous it is mentioned that, variables are always associated with some valid data type.  Data types are the ways to identify the type of data and associated operations, which can be performed on that data. In C++ data types can be classified as follows:



Simple / Built-in / Fundamental Data Types:

Built-in or Fundamental data types are atomic data types. Built-in data types are also referred as ‘Primitive’ data types. Here is given below a list of Primitive data types with range of values each can support and amount of memory occupies in terms of bytes.
Name
Type
Range of values
Memory size in Bytes
Integer



int
short int
signed int
unsigned int
long int
signed long int
unsigned long int
Integer
Short integer
Signed integer
Unsigned integer
Long integer
Signed long integer
Unsigned long integer
-32768 to 32767
-32768 to 32767
-32768 to 32767
0 - 65535
-2147483648 to 214748367
-2147483648 to 214748367
0 to 4294967295
2
2
2
2
4
4
4
Character



char
signed char
unsigned char
Character
Signed character
Unsigned character
-128 to 127
-128 to 127
0 to 255
1
1
1
Floating – point



float
double
long double
Float-point
Double floating-point
Long double floating-point
3.4e-38 to 3.4e+38
1.7e-308 to 1.7e+308
3.4e-4932 to 1.1e+4932
4
8
10

The void Data Type:

The void data type was introduced in ANSI C. The meaning of void can be taken as “Nothing / empty”. The void data type can be used to
  • Specify the return type of any function
  • To indicate an empty argument list
  • It can also be used to declare a generic pointer
The bool Data Type:
The data type bool has been added to to ANSI C++ to hold a Boolean value i.e. True or False. Bool data type variable can also be used in mathematical expressions. When a value of type bool is used with non-Boolean type expressions it is evaluated to integers. The bool type variables can be declared as follows:
bool status1;
status1 = true;
bool status2=false;

true represents to 1
false represent to 0
The wchar_t Data Type:
The data type wchar_t has been added to ANSI C++ to hold 16-bit wide characters. It is useful to represent the character sets of the languages that uses more than 255 characters, such as Jpanese.
Data type modifiers:
In C/C++ we have the keywords like signed, unsigned, long and short which are used to modify the size of data are known as Data type modifiers. Integer data types are short and signed by default; they can be signed or unsigned. Floating –point data types cannot be unsigned. Character data types can be signed or unsigned.
From the table given above you might have noticed that whenever a data type is prefixed with modifier long its memory size becomes just double. And also when a data type is changed from signed to unsigned, range of positive values it can support increase by double but size of memory still remains same.
Note: An Unsigned variable can support only positive values.

Derived Data Types:

The data types which are derived from the built-in or primitive data types are called as derived data types. These data types can be derived using declaration operators or punctuators.
Array:
An array is a derived data type as it can be derived from built-in data types. It is basically a named, consecutive and finite set of memory locations, which can hold multiple data items of its declared data type.
Example:
int ARR[5]; //Here ARR is an array of type integer having 5 (0 to 4) consecutive memory blocks
float ARR[5]; // Here ARR is an array of type floating-point having 5 (0 to 4) consecutive memory blocks
char STRING[4] = “XYZ” // it is an array of characters.

Functions:

A function in C++ is a named and finite set of C++ program statements. They are designed to do some specific task or to take some specific action(s). Functions are associated with return types, actual and formal argument list. Typically a function is associated with three tasks
  • Function prototyping
  • Function definition writing
  • Function calling
Example:
#include<iostream.h>

int sum(int, int); // prototype of function sum()
int sum(int x, int y)//Function definition, here x and y are formal arguments
{
return (x+y);
}

int main()
{
int a,b;
cout<<'\n Enter two numbers";
cin>>a>>b;
int ans =sum(a,b); //Function calling, here a and b are actual arguments
cout<<"\n Sum = "<<ans;
return 0;
}
Note:  more about function will be discussed in the related chapter.

Pointers:

A pointer is a special variable which holds the address of a normal variable of its own data type. The pointer variable can be declared with the help of a punctuator ‘*’ (astrick).
Example: 
int *ptr; //declared a pointer variable named as ‘ptr’ and is of type ‘int’
int num;
ptr = &num; // assigned the address of variable ‘num’ of type ‘int’ to the pointer variable.

Reference:

A reference variable is also a special variable. A reference variables is declared with a ‘&’ (reference) operator. A reference variable is used as an alias to another variable of same type.
Example:
//Program to demonstrate the use of a reference variable
#include<iostream.h>
#include<conio.h>
int main()
{
clrscr();
int num;
num = 6;
cout<<"\n Initial value in variable \'num\': "<<num;
int &nick_name=num;

nick_name+=10;
cout<<"\n Showing the value form variable \'num\': "<<num;
cout<<"\n Showing the value form the reference variable \'nick_name\': "<<nick_name;
getch();
return 0;
}
Output:

Here carefully observe the output. Initially variable ‘num’ was assigned with value 6. Variable named ‘nick_name’ which is a created as reference to variable ‘num’. So, the addition operation with the reference variable ‘nick_name’ is reflected back to the variable ‘num’

User-defined Data Type:

User-defined data types are the customized data type. It can be composed of a variety of built-in and derived data types (excluding function). A user-defined data type is specially designed to meet once programming needs.
 Structure:
A structure is composed of one or more built-in or / and derived data types (excluding function). Every element of the structure has separate storage space. So the size of a variable of structure type will have the memory space equal to the sum of memory spaces of its all individual elements. Keyword struct is used define a structure.

/*program to illustrate the fact – ‘the size of a variable of structure type will have the memory space equal to the sum of memory spaces of its all individual elements.’*/
#include<iostream.h>
#include<conio.h>
struct record{
int roll;
char name[30];
float marks;
};
void main()
{
clrscr();
record student;//’student’ is a variable of type record, which is a structure
cout<<"\n Size of each individual element of the structure are listed below:\n";
cout<<"\n Size of variable \'roll\': "<<sizeof(student.roll);
cout<<"\n Size of variable \'name\': "<<sizeof(student.name);
cout<<"\n Size of variable \'marks\': "<<sizeof(student.marks);
cout<<"\n-----------------------------------------------\n";

cout<<"\n Total size of structure variable \'student\': "<<sizeof(student);
getch();
}
Output:

Union:

A union is also composed of one or more built-in and / or derived data types (excluding function). Unlike structure it shares memory locations so memory conservation is possible. Keyword union is used to define a union. C++ will allocate enough storage in the variable of union type to accommodate the largest element in the union.
/* Program to illustrate the fact – ‘C++ will allocate enough storage in the variable of union type to accommodate the largest element in the union.’*/
#include<iostream.h>
#include<conio.h>
union record{
int roll;
char name[30];
float marks;
};
void main()
{
clrscr();
record student;
cout<<"\n Size of each individual element of the union are listed below:\n";
cout<<"\n Size of variable \'roll\': "<<sizeof(student.roll);
cout<<"\n Size of variable \'name\': "<<sizeof(student.name);
cout<<"\n Size of variable \'marks\': "<<sizeof(student.marks);
cout<<"\n-----------------------------------------------\n";

cout<<"\n Total size of structure variable \'student\': "<<sizeof(student);
getch();
}
Output:

Here carefully observe that the size of union variable i.e. ‘student’ is same as size of variable ‘name’

Enumeration:

An enumerated data type is another user-defined data type which provides a way for attaching names to numbers. The enum keyword automatically enumerates the defined list by assigning them 0,1,2 and so on. By default, the enumerators are assigned integer value starting with 0 for the first enumerator, 1 for the second and so on. However we can over-ride the default nature by explicitly assigning integer values to the enumerators.
Example:
enum book{eng, hindi=2, computer = 6};

//Program using enumeration
#include<iostream.h>
#include<conio.h>
enum vehicle{
bicycle,
bike,
car
};
void main()
{
clrscr();
int code;
cout<<"\n Enter a number";
cin>>code;
while(code>=bicycle && code<=car)
{
     switch(code)
     {
          case bicycle:
          cout<<"\n You can have a Bicycle\n";
          break;
          case bike:
          cout<<"\n You can have a Bike\n";
          break;
          case car:
          cout<<"\n You can have a Car\n";
          break;
     }
     cout<<"\n Enter a number: ";
     cin>>code;
}
getch();
}
Output:

Class:

class is also a user-defined data type, that can hold data and function. There are almost no difference in the syntax of a structure and a class. This is new data type is then used to declare objects. Thus a class is a logical abstraction where as an object has a physical existence. An object is an instance of a class. Thus it can be said that a class is a basis of OOP concept. The keyword class is used to define a class.
FMore about class you will able to learn in class XII
Example:
//Program demonstrating the use of class
#include<iostream.h>
class sample //sample is the name of the class
{
private:
int a,b,ans;
public:
sample( ) // constructor definition
{a = 6; b = 2;}
void sum(void) //member function definition
{
ans = a+b;
cout<<ans;
}
}; //class definition ends here
void main( )
{ sample Ob; //’Ob’ is the object of type class ‘sample’
Ob.sum( ); //calling of function ‘sum’ through object ‘Ob’
return;
}

Data Type Conversions:

Data type conversions are of two types: implicit and explicit.

Implicit Conversion:

When two or more different data types are mixed in an expression, C++ performs automatic data type conversion is known as Implicit or Automatic conversion. The compiler converts one of them to match the other, using the rule that the ‘smaller’ type is converted to the ‘wider’ type. Let’s see an example:

As it is very clear from the above figure that two different types of data were added and the final result came in float type. As float data type is wider then int data type. So, int is converted to float type. Figure given below illustrates this concept more.
The C++ compiler converts all operands upto the type of largest operand, which is called type promotion. This operation is done operation by operation. Steps followed by the compiler for type promotion are as follows:
  1. if either operand is of type long double, the other is converted to long double
  2. Otherwise, if either operand of type double, the other is converted to double
  3. Otherwise, if either operand of type float, the other is converted to float
  4. Otherwise integral promotion takes place on both the operands.
A char, int, short and enumerator (both in signed and unsigned versions) considered as int. if in a particular case int data type can represent all the values of the original type then, the value is converted to int, otherwise is converted to unsigned int. This is known as integral promotion.

Explicit Conversion (Type Casting):

 C++'s default type conversion rule can be overridden by specifying your own temporary type change. This is referred as Explicit type casting. C++ accepts two formats of type casting: 
I. (data_type) expression;
Example:
int i = 20;
float f;
f = (float) i; 
II. data_type(expression);
Example:
int i = 20;
float f;
f  = float(i);
Note** In above examples data type of 'i' which was int converted to 'float' type and stored in float type variable 'f'. If data type of higher width in converted to data type of lower width you will loose the information.
Example:
  float f = 20.55;
int i;
i = int(f); //In this case variable i will able to store only 20. The value .55 will be discarded.


Some important points to keep in mind while using Explicit Type Conversion:
  1. If double is converted to float, then there will be loss in precision. Moreover the original value may be out of range for target type.
  2. If floating – point type converted to integer type then there will be lose of fractional part. Moreover the original value may be out of range for the target type.
  3. If long type is converted to short type then original value will be out of range for the target type. 

Constants / Literals:

Constants or laterals are the data values that never change their values during the program execution.
C++ provides constants are of following types:
  • Integer constants
  • Character constants
  • Floating – point constants
  • String constants

Integer constants:

Integer constants are the whole numbers. Data value can be positive or negative i.e. can be preceded by a positive (+) or negative (-) sign. However using of a positive sign before an integer value is optional. An integer value can be further categorized as.
Decimal (Base 10) – An integer number consists of digits is considered as a decimal number unless it starts with a 0 (zero).
Octal (Base 8) – An integer value starts with digit 0 (zero) is taken as octal. An octal number contains digits from 0 to 7
Hexadecimal (Base 16) – An integer constant begins with 0X or 0x is called as hexadecimal constant. A Hexadecimal number contains 16 symbols i.e. 0 to 9 and A to F
Example:
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int dec,oct,hex;
dec=259;         //Decimal format
oct=0117;        //Octal format
hex=0xFF;       //Hexadecimal format;
cout<<dec<<"\t"<<oct<<"\t"<<hex;
getch();
}

Character Constant:

A single character enclosed with a pair of single quotation mark is known as Character constant. When C++ compiler encounters such character constant, it translates into a corresponding ASCII code and stores in the designated variable.
            Even non-graphic characters can be represented by using an escape sequence. An escape sequence is represented by a backslash (\) followed by a one or more characters. An escape sequence represents a single character. Following is a list of escape sequence used in C++.
Escape Sequence
Non_graphic Character
\a
\b
\f
\r
\t
\v
\\
\’
\”
\?
\On
\xHn
\0
Audible bell (Alert)
Backspace
Formfeed
Newline
Horizontal tab
Vertical tab
Backslash
Single quote
Double quote
Question mark
Octal number
Hexadecimal number
Null



Example:
//Program to demonstrate - how an ASCII code is associated with each character constant
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
char value1,value2;
value1='A';
value2='\n';
cout<<"\n value1 = "<<int(value1)<<" value2 = "<<int(value2);
getch();
}

String Constants:

Multiple characters enclosed with a pair of double quotation mark is treated as string constant. Each string constant is automatically terminated by a character ‘\0’ (NULL). Thus a string literal say – “xyz” is actually is represent as “xyz\0” . So, its size in memory is 4 not 3. It is to be noted that string is not a primitive data type. But internally it is treated as an array of characters.

Floating-point Constants:

Floating-point constant is a real number which holds a fractional part. A floating point constant must have one digit before and after decimal point. Floating-point constants can also be written in exponent notation. The exponent can be positive or negative. Example: 1.23456E-5 is equivalent to 0.0000123456. This is same as 1.23456 X 10 -5 . Thus an exponent notation is written with a ‘e’ or ‘E’ .
Following are some valid examples of real constants of float type.
-123.456          +123.456         1234.   +1.24E12         1.67E+10         +214E-5          1.25    
//Program to illustrate the use of various floating-point constants
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
float value1,value2,value3,value4,value5;
value1=1.23456E-5;
value2=1.5E+10;
value3=+1.33E10;
value4=0.000012345;
value5=1.25;
cout<<"\n value1 = "<<value1<<" value2 = "<<value2<<"\t"<<"value3 = "<<value3
<<" value4 = "<<value4<<"\nvalue5 = "<<value5;
getch();
}

Const Keyword:

C++ allows us to declare constants explicitly. Declaring a constant is just same as declaring a variable except its value cannot be changed. const keyword is used to declare a constant. Note that, while declaring a constant it must be initialized with a value.
Example:
const int x = 50; //here the value of x i.e. 50 cannot be changed during the program execution.

Punctuators:

There are some special characters used in C++ as separators are called Punctuators, these are also known as separators.:
  • Brackets [ ]. These two brackets are used for declaring single and multi-dimensional array subscripts:
Example; int num[5]; // declared a single dimensional array with 5 consecutive memory blocks
  • Braces{ }. These two braces are used to indicate start and end of compound dtatements.
Example:
if(<condition>)
{
…. do this…..
….. do this….
……………..
}
else
{
…. Do this …..
…… do this …..
}
  • Parentheses ( ). These two are used in function calls and in function parameters. It is also used to group loop conditions.
Examples:
if(a>b) && (a>c))
while(ch = = ‘y’)
{
:
:
}
  • Comma (,). It is used to separate two variable declarations in same line. Also used to separate the function arguments.
Examples:
int a,b,c;
sum(int x, int y)
  • Semicolon(;). It is used to terminate a C++ program line.
Example:
int a,b,c; //C++ program statement ends here.
  • Colo(:). It is used label the C++ statements.
Example:
goto TERMINATE
:
:
TERMINATE:
  • Asterisk (*). It is used in pointer declaration. It is also used as multiplication operator.
Example:
int *ptr
int total = num*2;
  • Ellipse (…). It is used as formal arguments list in a function prototype declaration.
Example:
void sum(…);
  • Equal sign (=). It us used to assign value into a variable.
Example:
int a = 0;
int total = num1+2;
  • Hash / Pound sign (#). It is used to invoke the preprocessor directive.
Example
#include<iostream.h>

No comments:

Post a Comment