Wednesday, 26 February 2014




Undefined behavior is nothing but  we cannot deduct how a application will react to some situation. Code will work fine without any semantic errors. But the output of the code was unpredictable.

C and C++ are most appropriate examples of such behavior.

For instance. If you declare a variable in c or c++, then you can use that variable without initializing it. Code will work fine for that situation. But the output of the code was unpredictable. It vary time to time. This behavior is called undefined behavior

HOW TO OVERCOME UNDEFINED BEHAVIOUR IN PROGRAMMING:
It is in the hands of the programmer to overcome the undefined behavior in programming.
There are also some tools available like valgrind,gdb  for pointing out these issues. Then always compile with –Wall (if your compiler is gcc) to overcome some of this issues.


WHY UNDEFINED BEHAVIOR:
The undefined behavior is allowed mainly to increase the efficiency and performance.
For eg consider the order of evaluation of function parameters.  some architecture will be fast when reading from left to right and vice versa.

DIFFERENCE BETWEEN UNSPECIFIED AND UNDEFINED BEHAVIOUR:
The undefined behavior and unspecified behavior both are different.
unspecified behavior is something where the implementation is undefined but it should conforms to standard. For eg evaluation of function parameters. Here the order of evaluation of function parameter is unspecified. It is up to the implementation.

Undefined behavior is something where we cannot predict the results. Here although it conforms to standards, here the result are unpredictable.
UNDEFINED BEHAVIOUR IN C AND C++:
1. USING THE VARIABLE WITHOUT INITIALIZATION:

when you use a variable without initializing then it leads to a undefined behavior. Because it use the garbage value. so its result is unpredictable at all time.

int a,b;b=a+10; // garbage value to b

2. FUNCTION WITHOUT A  RETURN STATEMENT:
As per semantics, the compiler will allow without return statement even if the return type of the function is other than void say int,float,double etc., But this will result in unpredictable results always.
int myfunction(){ // No return statement}int main(){ int a=myfunction();
}


3. VARIABLE SIZE OVERFLOW:

When the variable size overflows  then it will result in unpredictable results. For eg size of MAX_INT  is 65535. Then the following code will result in overflow. Here the if value of N is greater than the MAX_INT, the value of i never fails in the condition i<N because after variable i reaching the limit, it starts to count from 0 (INT_MIN). So the loop never ends.
for(i=0;i<N;i++){//Loop runs infinite times if N is greater than MAX_INT}

4. DEREFERENCING A DANGLING POINTER

When you free a memory after malloc. The memory will get freed. But the pointer will point to the same location even after the freeing process. Since the pointer refers to the freed memory. the pointer is called as dangling pointer. When you dereference a dangling pointer you will get the unpredictable results always.
char *p=(char *)malloc(sizeof(char)*5);
free(p); // Here memory deallocated but p points to same location. So p is a dangling pointer
*p=*p+1; //Unpredictable results
5. DEREFERENCING THE WILD POINTER:

The wild pointer is nothing but the uninitialized pointer. When you use a uninitialized pointer then it will return some garbage value
int *p;*p=*p+1; // undefined behaviour
6. RETURNING A ADDRESS OF LOCAL VARIABLE

When you return the address of the local variable, then it is also an undefined behavior.
int callme(){int a;return &a; // Scope of dies here. No use of passing a’s address}

7. CHANGING THE CONST CHAR POINTER
When you attempt to change the const char pointer then the result will be unpredictable.

char *p=”HELLO”;p[1]=’S’; // Lead to segmentation fault

in above snippet, the HELLO is string literal stored in read only memory. Here we are attempting to change the read only memory. Code works without any compilation error. But the segmentation fault error will occur.

Saturday, 22 February 2014

Context is used to connect two or more databases and it allows to switch between them in run time.


CREATING CONTEXT:

Context is created using the pseudo column sql_cursor.


sql_cursor mycursor;

The above declaration should be done inside the declare section of pro c/c++.


ALLOCATE THE CONTEXT:

The context should be allocated before they were used in the program.


EXEC SQL CONTEXT ALLOCATE :mycursor;

Note that for cursor allocation the same above statement is used but the clause context is removed.


USE THE CONTEXT:

We can switch between the context by using the following declaration.
The use statement should come before connecting to the database. Allocate is much similar to declaration.  


EXEC SQL CONTEXT USE :my_cusor;


DEFAULT IN CONTEXT:

You can swith to the default cursor by the following statement.
EXEC SQL CONTEXT USE DEFAULT;
The default is the keyword no semicolon comes before that.


SAMPLE PROGRAM



 #include"stdio.h"
Exec sql include sqlca;
int  main()
{
   exec sql begin declare section;
   char *usr1="usr1/usr1pwd@servicename1";
   char *usr2="usr2/usr2pwd@servicename2";
   char *usr3="usr2/usr2pwd@servicename3";
   sql_context usrcontext1;
   sql_context usrcontext2;
   int avg_mark;
   exec sql end declare section;
   exec sql whenever sqlerror go to sqlerr;

   // Connecting to default context

   EXEC SQL CONNECT :usr1;

   exec sql select AVG_MAR into :avg_mark from MARK_LIST where STUD_ID LIKE '121';
   printf("\n Avg Mark at connected database: %d",avg_mark);

   //allocating and connecting to usrcontext1

   EXEC SQL CONTEXT ALLOCATE  :usrcontext1;
   EXEC SQL CONTEXT USE :usrcontext1;
   EXEC SQL CONNECT :usr2;


   exec sql select AVG_MAR into :avg_mark from MARK_LIST where STUD_ID LIKE '121';
   printf("\n Avg Mark at connected database: %d",avg_mark);


   //allocating and connecting to usrcontext2


   EXEC SQL CONTEXT ALLOCATE  :usrcontext2;
   EXEC SQL CONTEXT USE :usrcontext2;
   EXEC SQL CONNECT :usr2;


   exec sql select AVG_MAR into :avg_mark from MARK_LIST where STUD_ID LIKE '121';
   printf("\n Avg Mark at connected database: %d",avg_mark);

   // Now i am connecting to default context database

   EXEC SQL CONTEXT USE DEFAULT;
   exec sql select AVG_MAR into :avg_mark from MARK_LIST where STUD_ID LIKE '121';
   printf("\n Avg Mark at connected database: %d",avg_mark);

   // Now i am connecting to usrcontext2  database

   EXEC SQL CONTEXT USE :usrcontext2;
   exec sql select AVG_MAR into :avg_mark from MARK_LIST where STUD_ID LIKE '121';
   printf("\n Avg Mark at connected database: %d",avg_mark);

   //By this way you can connect mutiple database and you can swith between them

   return 0;

sqlerr:
   printf("\nError in DB \n");

   return 0;
}


OUTPUT:

Avg Mark at connected database: 85.55
Avg Mark at connected database: 51.22
Avg Mark at connected database: 90.15
Avg Mark at connected database: 85.55
Avg Mark at connected database: 90.15


In above output note that 1st and 4th  line avg was same. This indicates that are connected to same database schema.

Monday, 17 February 2014


Apart from programming, template is one, which just defines the outline. Consider the leave letter template, which does not contain much information. As a template it contains only from address column but it does not have a from address. similarly it has a body section but it does not have for what purpose the leave is taken.
In c++, templates are much more similar to that. Here, in class template only the class name will be given while declaring. But which datatype the class uses will not be mentioned. This is more generic way of programming.
Then you may ask why there is need for template class?
Here the class does a same functionality for all datatypes. If template class was not there then you have to define the multiple class for each datatype that the class uses. But using templates we are creating only one class.

Real time example:

Consider the Arithemetic operation class. The datatype for the Arithemetic operation can be int, float, double. Inorder to define the multiple class we can just create the single template class and we can make specific whenever we are needed.

Syntax:

template <class type1> class template_class_name;
Eg:
template <class type1> class arithmetic_oper;

In above syntax, the template is keyword just to indicate the class is of type template. Then another new thing is <> brackets. while instantiation, the datatypes that are going to be used are mentioned there. In above we can allowed to instantiate using one type but we can give many as <class type1,class type2>.

DEFINING THE TEMPLATE CLASS:

This is just as normal class definition. In normal class definition you will be using the datatype as int. float etc for declaring the variable. But here you will be using the typename defined inside the angle brackets.
here type1 is identifier. This type1 can be int,float,double etc., 

This is decided while creation of object for the class.

template <class type1>class arithmetic_oper
{
   public:
      type1 variable_name;
     int fixed_type_int;
};


DIFFERENCE BETWEEN CLASS AND TYPENAME IN TEMPLATE:
There is no major technical difference between the class and typename. we can use them interchangeably. But at one rare case it is different. Need to explore that.


CREATING OBJECT FOR TEMPLATE CLASS:

arithmetic_oper <int> int_operation;

Here the arithmetic_oper is template class name. Here I want to make the class to use the int variable. so I have used int inside the angle brackets. I cannot give more than one type here. If I want to give more than one type then I need to declare the template class as <class type1,class type2>

CREATING TEMPLATE FUNCTION INSIDE THE  TEMPLATE CLASS:

Declartion of function template with new type inside the class template goes like this

template <class F_Type1> F_Type1  add(F_Type1,F_Type1);

Here the new type F_Type1 is created .
And the definition of template function goes like this
template <class c_Type1>
template <class type1>
type1 arithmetic_oper<c_Type1> ::  add(type1 a,type1 b)
{
   return a+b;
}
Here consider this, We have to specify the both templates such as class template c_Type1 and function template type1.

TYPE CASTING OF FUNCTION TEMPLATE:

consider the following snippet,
addition_value=(int)int_operation.add<int>(5.10,10);
Here the <int> represent the type casting to parameters. Here both parameter were different. If it was same, then compiler will auto deduct it. we are confusing the compiler in deducting the parameter type. So we explicitly indicate the compiler regarding parameter types. Then (int) is normal type casting. It stores the resultant value in to addition_value variable by typecasting to integer.

SAMPLE PROGRAM:

#include<iostream>
using namespace std;

template <class type1>
class arithmetic_oper; //declaring template

template <class type1>
class arithmetic_oper //defining template
{
   public:
      type1 variable_name; //Here we can change the datatype
      int fixed_type_int;  //cannot change the datatype

      // Using different type for function template
      template <class F_Type1> F_Type1  add(F_Type1,F_Type1);

      //Using same type as class for function template
      type1 sub(type1,type1);

};

template <class c_Type1>
template <class type1>
type1 arithmetic_oper<c_Type1> ::  add(type1 a,type1 b)
{
   return a+b;
}


template <class c_Type1>
c_Type1 arithmetic_oper<c_Type1> :: sub(c_Type1 a,c_Type1 b)
{
   return a-b;
}


int main()
{

   //Creating object as int using template
   arithmetic_oper <int> int_operation;
   int_operation.variable_name=10;
   printf("\nUsing a class as a integer :: %d ",int_operation.variable_name);
   
int addition_value=int_operation.add(5,10);
   printf("\nADDITION OF GIVEN VALUE IS %d",addition_value);
   addition_value=(int)int_operation.add<int>(5.10,10); // Type casting as int.
   printf("\nADDITION OF GIVEN VALUE IS with type casting %d",addition_value);


   //Creating object as double using template
   arithmetic_oper <double> double_operation;
   double sub_value=double_operation.sub(50.52,25.02);
   printf("\nSUBTRACTION OF GIVEN VALUE IS %f",sub_value);

   //Creating object as char using template
   arithmetic_oper <char> char_operation;
   char_operation.variable_name='A';
   printf("\nUsing a class as char type :: %c ",char_operation.variable_name);

   return 0;
}

OUTPUT:



Using a class as a integer :: 10
ADDITION OF GIVEN VALUE IS 15
ADDITION OF GIVEN VALUE IS with type casting 15
SUBTRACTION OF GIVEN VALUE IS 25.500000
Using a class as char type :: A 

Saturday, 8 February 2014

FILE EXTENSION
EXPANSION
compressed archive file
.rar
compressed archive file
.mpeg
motion picture expert group
.avi
audio and video interleave,developed by Microsoft in 1992
.art
clip art files
.bak
backup files
.cbl
cobol code
.doc
document file for word
.gif
graphics interchange format developed by compuserve for web
.htm
hypertext markup
.mp3
mpeg audio layer 3
.pdf
portable document file by adobe
.xml
extensible markup language
.3gp
 3rd generation partner ship project developed for 3g phones

ABBREVATION
EXPANSION
ADVANCED RESEARCH PROJECT AGENCY (FIRST INTERNET)
MICR
MAGNECTIC INK CHARACTER RECOGNISATION
PDA
PORTABLE DIGITAL ASSITANCE
IP
INTERNET PROTOCOL
TCP
TRANSFER CONTROL PROTOCOL
.EDU
 EDUCTIONAL INSTITUTIONS
.COM
COMMERCIL ENTITY
.ORG
NON PROFIT ORGANISTAION
.NET
NETWORK BASED ORGANISTION
TLD
TOP LEVEL DOMAIN(.EDU,.NET.ORG)
HTML
HYPER TEXT MARKUP LANGUAGE
URL
UNIFORM RESOURCE LOCATOR
HTTP
HYPER TEXT TRANSFER PROTOCOL
ARPA
ADVANCED RESEARCH PROJECT AGENCY (FIRST INTERNET)
MICR
MAGNECTIC INK CHARACTER RECOGNISATION
PDA
PORTABLE DIGITAL ASSITANCE
IP
INTERNET PROTOCOL
TCP
TRANSFER CONTROL PROTOCOL

Wednesday, 5 February 2014

What is copy constructor?

As the name suggests the constructor that used to copy the value of the one object to the other object while creating is called as copy constructor . So we are calling it  as a copy constructor.  Copy constructor, if not defined by the programmer then compiler will create its own. 
In this case normal constructor will not be called and as normal constructor copy constructor will not have return type and have same name as class name.
In other words,
what is constructor? It is used to initialize the objects .
what is copy constructor? It is used to initialize the objects with other objects while creating it.


When copy constructor is called ?

Ø  when you pass an “object as a value” copy constructor is called. Don’t just confuse with the object as value. It is same as call by value. Here instead of variable we were using the objects.
Fruits apple;  //Fruit is class, apple is object
callme(apple);  //object as value
The above code is similar to the following….
int a;
callme(a); //variable as value

I hope you have understand the difference between these two. so, coming to our topic copy constructor is called whenever you pass an object as a value.
And another important noting point is the copy constructor will not call again and again when we use object as a value. It will call only at  the time of object creation as above mentioned example.

Ø  when you return a object in function, the copy constructor will be called.
Fruits callme(Fruits apple)
{
…..
      return apple;   // returning object of class Fruit
}

Ø  Next whenever you initialize the object with other object the copy constructor will be called.
Fruits apple, orange;
apple=orange; // Initializing orange object with apple
Fruits pinapple(apple); //Here too copy constructor called

Syntax for copy constructor :
class myclass
{
           myclass (const myclass &obj_passed)
              {
          //copy constructor code
          //create a new copy of object here
     }
}
In above syntax :
obj_passed is the reference of the object from which we are going to copy the value.  Note the const keyword in parameter.



What happens if copy constructor is not created by user?
So, are you wondering what happens if copy constructor is not created by the user. You just don’t worry compiler will create it. Even if copy constructor is not defined the following code will work.
Fruit apple=orange;
where orange and apple are objects and fruit is class. Here we were assigning a orange object with the apple. In a compiler defined copy constructor, initialization of the object takes place “member wise”.  This process is called is called as Shallow Copy. Hope you understand member wise, Data members of the source object will be copied to destination object’s Data members.

Where the copy constructor is must?

When we fail to create a copy constructor the compiler will create it by own. In such cases if member of the object is pointer then address will be copied in the object created by the copy constructor. So object created by class and a copy constructor will share a same memory location. In such case when destructor is called, no problem for the 1st object, memory will be deallocated but in the second case the application will crash. So in case of pointers the copy constructor is must.

The thread is the process of executing the set of instructions independent from each other by sharing the resources.
Then process is also a set of instructions, which produce certain output.
What makes the difference between the thread and process? Here are few…
Thread
Process
Thread share the same address space
Process will have different address space
Context switching is slow here.
Context switching is faster between process
Thread depend upon the process.
Process is typically independent

In above difference context switching is something storing and retrieving the states of the threads.

Multithreading:
Multithreading is the parallel execution of the programs by sharing the resources like memory.

Multithreading in C++:
C++ doesn’t have an built-in program to handle the threads. We need to use the API to handle the threads. POSIX(Portable operating system interface) threads provides an API to create and manipulate threads. POSIX threads usually called as an pthreads.
POSIX is an family of IEEE standard which provides the lots of API’s.
All the implementation of the POSIX thread are under the pthread.h
All functions of POSIX threads begin with a prefix “pthread_”.
Creating a thread:

PROTOTYPE:
pthread_create(pthread_t *thread_info, const pthread_attr_t *attribute, function_name, (void *)myfunction_args)
EXAMPLE:
pthread_t mythread;
pthread_attr_t thread_attr;
pthread_create(&mythread, &thread_attr, my_function, &i)

argument
Description
Need for this argument
pthread_t *thread_info
Unique identifier for the thread. Contains the information about the thread you were creating. It is of Pointer type. Pass the variable of struct pthread_t.
You will have an multiple threads in your program, to identify and manipulate a single thread this argument becomes useful.
const pthread_attr_t *attribute
Attributes to the thread are set here. Attributes in thread like priority, etc
Among several threads if you need to set priority to the particular thread, you can configure with this pointer
myfunction
This method is called after the successful creation of thread. The code that should be executed under this thread can be placed inside that function. If you need to specify the argument. Don’t do it here. The next parameter is used for passing a argument for the function “myfunction”
The code that is need to execute under the created thread can be placed inside the “myfunction”.

(void *)myfunction_args
The arguments for the myfunction is given here. It is of void pointer type.  The reason why given as void pointer is, there is no possibility that programmer will pass a int or float to the function, so in general it is passed as a void pointer. We can convert to any datatype further.
This argument is needed because if programmer intend to pass argument for a myfunction then he can use this argument to do so. If programmer wishes no argument is needed then he can pass NULL.

passing paramter as null:
You can configure the parameter of the pthread_create as NULL which indicates that the default values should be taken.
For instance,
pthread_create(&mythread, NULL, my_function, NULL)
In above statement, mythread will be created by taking the default attributes. Because the the second parameter is given as NULL. If you give the fourth parameter as NULL. Then the void pointer variable will be assigned as NULL.
This not means the creating the myfuntion with no arguments. Don’t confuse with that. It will just assign the NULL value to the void pointer.
Then your thinking will be what about configuring the 1st and 3rd parameter as NULL. If you pass them as NULL then your code will become useless, this is because if create thread without thread function, then where the code for that thread created.

synchronization in threads:


THREAD POOL:
Thread pool is the series of threads which is usually placed in the queue for performing some tasks. The input and output to the thread pool might be queue. Thread in thread pool will process the input queue one by one and places the result in result queue.
Threads are not destroyed after the completion of its tasks. After completion of task thread will take a new task or it will goes to sleep state.

The following scenario may occur depend upon the needs,
1.      Thread will terminate or sleep when allocated task in completed

Thread pool is much useful because.
1.      It reduces the overhead of creating and destroying threads.

2.      Thread creation will take much time. So It reduce the wait time for the client.