Wednesday, 13 March 2013

Unusual behaviour of signed and unsigned modifier

Signed and unsigned modifiers are not compatible with float and double.But if we use them with double and float there is only display an intellisense error and when we compile the program ,it shows nothing as an error.So we should be attentive while using signed and unsigned because compiler shows nothing as an error and compiler takes something as a default.Here is a program to describe the behaviour of signed and unsigned :-



 Here we can see that when signed and unsigned float printed as a float it gives zero.Similarly in the case of signed and unsigned double it also returns zero.Here we can seen one more thing that the value of integer a when printed as a float then it also returns zero.It means we must never use an integer as float.

Monday, 4 March 2013

Qualifiers in C

Today ,I run a program for qualifiers in C.There are basically three qualifiers in C which are used in different styles according to their use :-

1)volatile:-The volatile qualifier maintain consistency of memory access to data objects.The volatile keyword is intended to prevent the compiler from applying any optimization on the code that assume values of variable cannot change "on their own".The volatile keyword is used to declare that an object can be modified in the program by something such as the operating system,the hardware or a concurrently executing thread..It can be used with four types:-

int * volatile ic=&v4;        //a volatile pointer to an integer ,the value of integer can be changed.
volatile int *ci=&v5;        // a pointer to a volatile integer the value of integer cannot be changed .
int volatile *icptr=&v6;       //same as second
volatile int* volatilet cicptr=&v7;       //It is a volatile pointer to a vloatile integer so either  the integer can be changed or the pointer to point anything else.

                                                             The volatile object each time read from memory each time their values is needed and written back to memory each time they changed.The volatile qualifier declares a data object that can its value change in ways outside  the control or detection of the compiler .The compiler is thereby notified not to apply certain optimization to code referring to the project.We can understand it with this example:-

int xyz=100;
while(xyz==100)
{
//code
}

 This program gets compiled ,the compiler may optimize this code.If it finds that the program never ever makes any attempt to change the value of xyz.So it may optimize the code by changing it from "while(xyz==100)"  to "while(true)" because it is slow to compare each time the value of xyz to 100.
                                            But this is not desirable in each case to optimize the code because it is possible in the above case the value of xyz may be changed by an another cause outside the program.which is compiler is not aware of.So In this case we declare the integer xyz as a volatile and it stops the compiler to optimize the code.

volatile int xyz=100;

In C /C++ volatile keyword is intended to:
1)allow access to memory mapped devices
2)allow uses of variables between setjmp and longjmp
3)allow uses of  sig_atomic_t variables in signal handlers

We can use the following program to understand the volatile keyword:-


#include <iostream>
#include <windows.h>
using namespace std;

volatile bool Sentinel = true;
int CriticalData = 0;

unsigned ThreadFunc1( void* pArguments ) {
   while (Sentinel)
      Sleep(0);   // volatile spin lock

   // CriticalData load guaranteed after every load of Sentinel
   cout << "Critical Data = " << CriticalData << endl;
   return 0;
} 

unsigned  ThreadFunc2( void* pArguments ) {
   Sleep(2000);
   CriticalData++;   // guaranteed to occur before write to Sentinel
   Sentinel = false; // exit critical section
   return 0;
}

int main() {
   HANDLE hThread1, hThread2; 
   DWORD retCode;

   hThread1 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&ThreadFunc1,
      NULL, 0, NULL);
   hThread2 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&ThreadFunc2,
      NULL, 0, NULL);

   if (hThread1 == NULL || hThread2 == NULL)       {
      cout << "CreateThread failed." << endl; 
      return 1;
   }

   retCode = WaitForSingleObject(hThread1,3000);

   CloseHandle(hThread1);
   CloseHandle(hThread2);

   if (retCode == WAIT_OBJECT_0 && CriticalData == 1 )
      cout << "Success" << endl;
   else
      cout << "Failure" << endl;
}

In this we can see that there is two thread handler declare which called two thread functions which are executed parrallely.In the first function we can see that the Sentinel is true so the function is in an infinite loop .When the second function starts its execution parrallaly the value of critical data incremented to one and the the value of Sentinel become false  and the value of critical data is printed one. 


2)Const:-The const qulaifier explicitly declares an data object that cannot be changed .Its value is set at initialization.We cannot use a const variable in expression requiring a modifiable lvalue.It can be used with four types:-
int * const ic=&v4;        //a const pointer to an integer ,the value of integer can be changed.The value of pointer cannot be changed
const int *ci=&v5;        // a pointer to a const integer the value of integer cannot be changed .The value of pointer can  be changed   .

int const *icptr=&v6;       //same as second
const int* const cicptr=&v7;       //It is a const pointer to a const integer so neither  the integer can be changed nor the point to anything else.
These 4 variation we can easily understand with these figures:-




We can easily understand it with the help of program snapshot:-

 





























*Commented lines are shows that these  const variables are not modifiable which we explained above.

3)restrict:-Basically there are two keywords _restrict and restrict_declspec.The _restrict keyword is valid only on variables .When restrict is used ,the compiler will not propagate the no-alias property of a variable.That is ,if you assigned a _restrict variable to a non-restrict variable ,the compiler will not imply that the non-_restrict variable is not aliased.The _restrict keyword similar to the restrict_declspec but _restrict can be used in C or C++ program.The restrict_declspec  is not a keyword in standard C/C++.It is a keyword C99 compiler .So if we use C99 compiler then it works fine.The restrict qualifier is only applied to a pointer .We know that a pointer is the address of a location in the memory.More than one pointer can access the same chunk of memory and modify it during the course of a program.But If we use restrict type of qualifier,it indicates to compiler if the memory addressed by the restrict-qualified pointer is modified ,then no other pointer will access the same memory .We can declare a restrict pointer by following syntax:-


 int * __restrict  f;

Here is snapshot for behaviour of a restricted variable.




Sunday, 3 March 2013

Behaviour of some Math.h functions

Today,I use some basic type of math.h functions and try to understand their behaviour.Here are some math.h functions which we use for study:-
1)abs
2)fabs
3)ceil
4)floor

1) abs :-This function returns absolute value of parameter.If a parameter having a value of -4 then it returns its value 4.It always takes and return int value.
2)fabs:-This is also having behaviour like abs But It always takes a double & returns double.F stands here
for floating-point argument.
3)ceil:-It calculates the ceiling value of parameter.It mean if a parameter having a value 4.1 then it returns 5 and value of a parameter is -4.1 then it returns 4.
4)floor:-It calculates the floor value of parameter .It mean if a parameter having a value 4.1 then it returns 4 and value of a parameter is -4.1 then it returns 5.

here is the snapshot of this program:-





Rounding a deimal number in C:-We can round the decimal number in C with following two methods:-

1)   FLOATVALUE = FLOOR(FLOATVALUE+0.5);
2)  FLOATVALUE = INT (FLOATVALUE+ 0.5);

Sunday, 24 February 2013

Right Shift of signed,unsigned char & int


Today ,I wrote a program for right shift of signed & unsigned int & char .Here we get some strange things.We need to understand it through program,Here is the snapshot of the program:-


Here we can see that signed char sc is different printed compare to inserted value.This is an anomaly.This is done because the the MSB is 1 But in case of signed char sc1 the printd value is same as inserted .This is because of value of MSB which is zero.In these if we take right shift of both we seen that In the case of  sc the value is unchanged because if we right shift the signed char or int it right shift the all bits & MSB equal to the MSB of original value either it is zero or one.In the case of unsigned char & int it right shift all the bits & MSB becomes Zero.These changes we can easily seen in the program.In the case of si & sc there is no change in right shift because MSB is one.  

Wednesday, 30 January 2013

Shift Operator (signed/unsigned)

Shift operator should be used very carefully .Because a little change in shift operator makes a major change in output.So it is very necessary to understand how it is internally work.Today I run a program which explains about shift operator .We need to take many signed & unsigned int & char variables.Then assign them some value.After performing right shift operation we conclude that the value of an integer become half of the previous value if we right shift the value by 1.Thus as we right shift by different values our previous value become half of its previous value.If we right shift a char say B by 1 which has a ASCII value 66 then it converts   char which has a ASCII value 33.The Same theory is applied to conversely applied to the right shift which double the previous value if we right shift by 1.If we right shift by 4 then it doubles the value 4 times .So It very useful in various opearation.    

Tuesday, 22 January 2013

Creating and using a DLL in C

Today I create a dll in C on microsoft visual studio 2010.Following are the snapshots of steps which we take during creating a dll in  microsoft visual studio 2010.








   After clicking finish we see several type of files in the project which are shown in below snapshot.


where temp is the name of project & cpp file.
In the temp.cpp file we need to write the definition of function & header files included in function writen in either temp.cpp or temp.h.Then we need to run which create temp.lib file in directory.By adding this temp.lib file into any project we easily use the dll only by adding used header in function into .h or .cpp file & calling the function.
we need to write __declspec (dllexport) for Cpp file & extern "C" __declspec (dllexport) for C file while creating library.



Here are some important keyword used in creating and using DLL:-

__declspec:-It is a storage class specifier .It uses various storage class attribute to enable various usage of it.

dllexport:-dllexport storage class attribute enables us to export function ,data & objects from the dll.Declaring function as dllexport eliminates the need for a module definition file ,at least with respect to the
specification of exported functions .Note that dllexport replaces the _export keyword .If a class is marked declspec (dllexport ),any specialization of class templates in the class hierarchy are implicitly marked as declspec(dllexport ).This means templates are explicitly instantiated and its member must be defined .The declaration of dllexport must use extended attribute syntax and the _declspec keyword.
Ex:-


__declspec( dllexport ) void func();


dllimport:-dllimport storage class attribute enables us to import function ,data & objects from the dll.The declaration of dllimport must use extended attribute syntax and the _declspec keyword.
Ex:-


__declspec( dllimport ) int i;

naked:-For the function declared with the naked attribute ,the compiler generates code without prolog and apilog code.Naked functions are particularly useful in writing virtual device driver.The naked code is only valid on x86 and is not available on x64 or itanium.
Ex:-


__declspec( naked ) int func( formal_parameters ) {}

Friday, 7 December 2012

Dynamic memory Allocation in 2-D Array


Today I wrote a program for dynamic memory allocation in 2-D array using malloc .We use  the 2-D  array as a 1-D .First of all we take a double pointer which stores the adress of a 1-D array.In this 1-D array we store the adresses of first location of each row.