Wednesday 27 March 2013

Structure of RAM and storage of variables during program in RAM

We know that If we execute a program then it goes into RAM and then all operation perform and we get a exe to display the output .So it is very important to know the structure of RAM.Here is a snapshot for Ram structure:-


Here we can see that the RAM have the extra segment at the top of it which has the highest address.Below it there is a stack segment,then data segment ,then code segment and at the lowest ROM section.Thus the ROM section has the lowest address.Now can we can study briefly about all of these  five parts:-

(1) Extra segment:-Extra segment is the topmost part of the RAM.It has the highest address.It stores the far pointers and used for keyboard buffer and video buffer.

(2)Stack segment:-Stack segment have the two main parts:-stack and heap.In Stack memory is allocated towards top to bottom while in heap memory is allocated towards bottom to top manner.We can understand  here with the help of these snap shot that what part of program they contains in program execution:-

                                           
(3)Data segment:-Data segment also have two parts.The first one is bss which stands for block started by symbol and the second one is data.We can understand what kind of data these two parts contains during execution of program with the help of these snapshot:-



(4)Code segment:-Code segment have the program instructions in it mainly contains body of program during program execution.

(5) ROM section:-It mainly stores information about the ram configuration.


Here some important information about default storage class specifier for variables and function is following:-

(1)For external declarations (outside a function) the default storage class specifier will be extern and for internal declarations(inside a function) it will be auto. 

(2)default storage class specifier for functions  is always extern.

Saturday 23 March 2013

Some more keywords....

I run a program for complex numbers in C .There are various type of complex number keyword declared in
#include <complex> .Here are some:-

1)_complex                                    //takes double
2)_C_double_complex                   //takes double
3)_C_float_complex                       //takes float
4)_C_ldouble_complex                  //takes long double

I have used them in my program and perform various operation like addition ,substraction,multiplication and division.Here is the program and output:-

#include<iostream>
#include<stdio.h>
#include<conio.h>
#include<msclr/safebool.h>
#include<complex>

void main()
{
bool a=false; //C++
//printf("boola=",a);
_complex c={12.66,34.787};
_complex d={1,34};
_complex e={(c.x+d.x),(c.y+d.y)};
printf("%lf\t%lf\n",e.x , e.y);
_C_double_complex a={12.34,65.7};
_C_double_complex b={2.34,65.7};
_C_double_complex g={a._Val[0]-b._Val[0],a._Val[1]-b._Val[1]};
printf("%lf\t%lf\n",g._Val[0] , g._Val[1]);
    
_C_ldouble_complex f={234.79345,12.64233};
_C_ldouble_complex h={1,2};
_C_ldouble_complex i={f._Val[0]*h._Val[0],f._Val[1]*h._Val[1]};
printf("%Lf\t%Lf\n",i._Val[0] , i._Val[1]);
_C_float_complex j={11.89,2.001};
_C_float_complex k={1,2.001};
_C_float_complex l={j._Val[0]/k._Val[0],j._Val[1]/k._Val[1]};
printf("%f\t%f\n",l._Val[0] , l._Val[1]);
_getch();
}

Output:-

13.660000       68.787000
10.000000       0.000000
234.793450      25.284660
11.890000       1.000000

*Here we use an another variable bool which takes two values true and false.It is declared in     header #include<msclr/safebool.h> .

Exception handling in C

Exception handling provides us a special type of facility in C.It handles the run-time errors occurred in the program.In the large programs it is very difficult to handle these type of exceptions.Some minor mistakes like divide by zero can create and interrupt in execution of a large program.So it is very difficult to find these smaller problems in a many thousand lines code.So to escape from these problems we use exception handling.There are following four keywords used in exception handling in C:-

  1. __try
  2. __finally
  3. __except
  4. __leave
1)__try :-__tyr is a keyword in C which is used in __try-__finally and __try-__except statemnt.A part of program in which there is chance of exception occurring that part of program write into this part.

2)__leave:-The __leave keyword is valid within a __try -__finally statement it jump to the end of try-finally.The termination handler is executed .Here __leave keyword jump the control to the finally when an exception is occur.We can seen it from this program:
3)__finally:-__finally gives a guarantee execution of a portion of a program when execution of a block code is interrupted.

int a=10,b=0;
__try
{
if (b == 0)
{
__leave;
}
c=(a/b);
cout<<"c="<<c;
}
__finally
{

cout<<"program terminates now";
}

4)__except:-_It is used in __try-__except statement .It is use as exception handler .It uses filter to catch the exception.If an exception occurs during execution of the guarded section or in any routine the guarded section calls, the __except expression (called the filter expression) is evaluated and the value determines how the exception is handled. There are three values:


EXCEPTION_CONTINUE_EXECUTION (–1)   Exception is dismissed. Continue execution at the point where the exception occurred.
EXCEPTION_CONTINUE_SEARCH (0)   Exception is not recognized. Continue to search up the stack for a handler, first for containing try-except statements, then for handlers with the next highest precedence.
EXCEPTION_EXECUTE_HANDLER (1)   Exception is recognized. Transfer control to the exception handler by executing the __except compound statement, then continue execution after the __except block.


It is used in following way:-


int* p = 0x00000000;
__try
{
__try
{
puts("Exception occured");
*p = 13;
//c=(a/b);
}

__finally
{
printf("%s","In finally ...exception handler");
}

}

 __except(filter(GetExceptionCode()))
{
puts("in except");
    }


//

int filter(unsigned int code)
//int filter(unsigned int code, struct _EXCEPTION_POINTERS *ep)
{

   puts("in filter.");

   if (code == EXCEPTION_ACCESS_VIOLATION || code ==STATUS_INTEGER_DIVIDE_BY_ZERO)
   {

      puts("caught AV as expected.");

      return EXCEPTION_EXECUTE_HANDLER;

   }

   else
   {

      puts("didn't catch AV, unexpected.");

      return EXCEPTION_CONTINUE_SEARCH;

   }

}

Various datatypes and their initialization

We can initialize variables with different type.I run a program for it which has following codes:-


#include<stdio.h>
#include<conio.h>
void main()
{
int a1=5;
int a2='5';
int a3=5.5; //intialising with double value
int a4=5.5f; //initialising with float value
int a5=5.5F; //initialising with float value
int a6=5.5l; //double
int a7=5.5L; //long double
int a8=0xff;  int a8a=0xffffffff;  int a8b=0xfff;  int a8c=0xffff;
int a9=0xFF;
int a10=0123; //Octal   int a=06; //octal
printf("a=%d\n",a1);
printf("a2=%lf\n",a2);    // double
printf("a3=%f\n",a3);   //float
printf("a4=%f\n",a4);   //float
printf("a5=%lf\n",a5);   //double
printf("a6 =%Lf\n",a6);//long double
printf("a7 =%Lf\n",a7);//long double
printf("a8 =%Lf\n",a8);//long double
printf("a8a =%Lf\n",a8a);//long double
printf("a8b =%Lf\n",a8b);//long double
printf("a8c =%Lf\n",a8c);//long double
printf("a9=%Lf\n",a9);//long double
printf("a10 =%Lf\n",a10);//long double

        auto  a=2;              //auto
        auto  b=3.8;            //double
        auto  b1=3.8f;          //float
        auto  b2=3.8F;          //float
        auto  b3=3.8l;         //double
        auto  b4=3.8L;          //long double
        auto c='h';            //char
        printf("a=%d\n",a);
        printf("b=%lf\n",b);    // double
        printf("b1=%f\n",b1);   //float
        printf("b2=%f\n",b2);   //float
        printf("b3=%lf\n",b3);   //double
        printf("b4 =%Lf\n",b4);    //long double
        printf("c =%c\n",c);   //char


char a12='a';//char
char a13=20;//int
char a14='\x40';//hex
char a15='\45';  //octal
char a16='\u0040'; //unicode  16 bit
char a17='\U00000040'; //unicode  32 bit
   printf("a12=%c\n",a12);
        printf("a13=%c\n",a13);  
printf("a14=%c\n",a14);
printf("a15=%c\n",a15);
        printf("a16=%c\n",a16);
        printf("a17=%c\n",a17);
   

char* a18="abdb";
char* a19="\x0040"; char* a20="\x40\xff";
char* a21="\334"; char* a22="\334\100";
char* a23="\u00ff"; char* a24="\u00ff\u00ff";
char* a25="\U000000F6"; char* a26="\U000000F6\U000000F6";
char*a59="\U000000F6\u00ff\x10\100";
        printf("a18=%s\n",a18);
        printf("a19=%s\n",a19);  
printf("a20=%s\n",a20);
printf("a21=%s\n",a21);
        printf("a22=%s\n",a22);
        printf("a23=%s\n",a23);
   printf("a21=%s\n",a24);
        printf("a22=%s\n",a25);
        printf("a23=%s\n",a26);
printf("a59=%s\n",a59);


wchar_t a27='a';
wchar_t a28=L'a';
wchar_t a31=20;
wchar_t a32='\x40';
wchar_t a35=L'\x79';
wchar_t a36='\33'; wchar_t a37='\51'; wchar_t a38=L'\334'; wchar_t a39=L'\51';
wchar_t a40='\u00ff'; wchar_t a41='\u00ff'; wchar_t a42=L'\u00ff'; wchar_t a43=L'\u00ff';
wchar_t a44='\U000000F6'; wchar_t a45='\U000000F6'; wchar_t a46=L'\U000000F6'; wchar_t a47=L'\U000000F6';
wprintf(L"a27=%lc\n", a27);
wprintf(L"a28=%lc\n", a28);
wprintf(L"a31=%lc\n", a31);
wprintf(L"a32=%lc\n", a32);
wprintf(L"a35lc=%lc\n", a35);
wprintf(L"a36=%lc\n", a36);
wprintf(L"a37=%lc\n", a37);
wprintf(L"a38=%lc\n", a38);
wprintf(L"a39=%lc\n", a39);
wprintf(L"a40=%lc\n", a40);
wprintf(L"a41=%lc\n", a41);
wprintf(L"a42=%lc\n", a42);
wprintf(L"a43=%lc\n", a43);
wprintf(L"a44=%lc\n", a44);
wprintf(L"a45=%lc\n", a45);
wprintf(L"a46=%lc\n", a46);
wprintf(L"a47=%lc\n", a47);

wchar_t* a48=L"a"; wchar_t* a49=L"abdsf";  
wchar_t* a50=L"\x40"; wchar_t* a50a=L"\x1079";
                wchar_t*                    a51=L"\x7910\x1879\x7979\x0056";
wchar_t* a52=L"\333"; wchar_t* a53=L"\333\33\333";
wchar_t* a54=L"\u00ff";         wchar_t* a55=L"\u00ff\u00ff";
wchar_t* a56=L"\U000000F6"; wchar_t* a57=L"\U000000F6\U000000F6";
wchar_t*a58=L"\U000000F6\u00ff\x1079\x10\345tyur1233$#%";
wprintf(L"*a48=%s\n", a48);
wprintf(L"*a49=%s\n", a49);
wprintf(L"*a50=%s\n", a50);
wprintf(L"*a50a=%s\n", a50a);
wprintf(L"*a51=%s\n", a51);
wprintf(L"*a52=%s\n", a52);
wprintf(L"*a53=%s\n", a53);
wprintf(L"*a54=%s\n", a54);
wprintf(L"*a55=%s\n", a55);
wprintf(L"*a56=%s\n", a56);
wprintf(L"*a57=%s\n", a57);
wprintf(L"*a58=%s\n", a58);

_getch();
}



Output:- 



a=5
a2=0.000000
a3=0.000000
a4=0.000000
a5=0.000000
a6 =0.000000
a7 =0.000000
a8 =0.000000
a8a =0.000000
a8b =0.000000
a8c =0.000000
a9=0.000000
a10 =0.000000
a=2
b=3.800000
b1=3.800000
b2=3.800000
b3=3.800000
b4 =3.800000
c =h
a12=a
a13=¶
a14=@
a15=%
a16=@
a17=@
a18=abdb
a19=@
a20=@
a21=▄
a22=▄@
a23=
a21=
a22=÷
a23=÷÷
a59=÷ ►@
a27=a
a28=a
a31=¶
a32=@
a35lc=y
a36=←
a37=)
a38=▄
a39=)
a40=?
a41=?
a42=
a43=
a44=?
a45=?
a46=÷
a47=÷
*a48=a
*a49=abdsf
*a50=@
*a50a=?
*a51=???V
*a52=█
*a53=█←█
*a54=
*a55=
*a56=÷
*a57=÷÷
*a58=÷ ?►σtyur1233$#%


 Following intialization has their own meaning:-

'\ooo': char with octal value
'\xhh':char with hex value
'\u':16-bit, assumed UTF16
'\U'-32-bit, assumed UCS-4

*L is used for declare a wide character literal or wide char string literal.

Friday 22 March 2013

Use of some specific keyeword


Here are some important  keywords which are very useful for us.So it is very important to know about them.


  1. auto
  2. enum
  3. register
  4. typedef
  5. extern
  6. union
  7. const
  8. continue and break 
  9. static
  10. __inline
  11. inline
  12. mutable
  13. thread_local
(1)auto:-auto is a keyword used to declare an automatic storage class.It is declared as following types :-

auto  a=2;              //auto
auto  b=3.8;            //float
auto c='h';            //char

 auto  b1=3.8f;          //float 
 auto  b2=3.8F;          //float
 auto  b3=3.8l;         //double
 auto  b4=3.8L;          //long double 
 printf("a=%d\n",a);    //int 
printf("b=%f\n",b);    // float
printf("c =%c\n",c);   //char

(2)enum:-The enum data type data type gives us a chance create our own data types and define what value that data type can take.We can use enum in our progran in following manner

enum day{sun,mon};
enum day d;
d = mon;
printf("%d\n ",sun);
printf("%d\n",mon);

here if we want to initialize d with any other value rather than sun ,mon then it cause an error.If we want to print the value of sun ,mon then it gives 0 and  1 respectively because by default value in enum intilialize with zero.

(3)resister:-resister is also a storage class used to faster access of variable because the storage will be done in CPU registers .It is a hint to the compiler that the variable will be heavily used and that  recommend it will be kept in a processor register if possible.We can declare a datatype register in following manner:-

register int ri=98;

(4)typedef:-typedef keyword provide us to rename a variable datatype into a short and meaningful way.
Ex:-
                typedef unsigned long int ULI;
                 ULI a;

(5)extern:-extern is also a storage class specifier .It is used for the use a variable which is initialized in another file in same project.When we use extern modifier with any variables it is only declaration i.e. memory is not allocated for these variable.We can declare register keyword in following manner:-

extern int ei=23;

(6)union:- union is a data type in C which is similar to structure in declaration and use but different in memory allocation.  

union a
{
char name[4];
int sal;
};
union a detail;
detail.sal=1024;
printf("detail.name[0]=%d\n",detail.name[0]);
printf("detail.name[1]=%d\n",detail.name[1]);
 printf("detail.name[2]=%d\n",detail.name[2]);
printf("detail.name[3]=%d\n",detail.name[3]);
printf("detail.sal=%d\n",detail.sal);

here char name and int sal uses same memory location .Here printf function prints 0,4,0,0,1024 respectively.
because the 1024 stored in following manner for 32-bit  :-


7)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.


8)continue and break:-break keyword is used in that case when in a loop an special condition is satisfied and we want to exit from the loop.For example:-

for(int i=0;i<5;i++)
{
if(i==3)
{
break;
}
printf("%d\n",i);
}
continue keyword is used in that case if we want to take control to the beginning of the loop then it is used.
We can use continue in following manner:-

for(int j=0;j<5;j++)
{
printf("%d\n",j);
if(j==3)
{
continue;
}
printf("%d\n",j);
}

(9)Static:-static is also a storage class specifier used in C/C++.It also stores variable in memory.The default initial value is zero.The value of the variable persists between different function calls.We can use a static datatype  in following manner:-

  

#include <stdio.h>

void func() {
        static int x = 0; // x is initialized only once across three calls of func()
        printf("%d\n", x); // outputs the value of x
        x = x + 1;
}

int main(int argc, char * const argv[]) {
        func(); // prints 0
        func(); // prints 1
        func(); // prints 2
        return 0;
}



(10)__inline:-This function copy a function body whenever we call a funcion. The __inline and __forceinline keywords are available in both C and C++. For compatibility with previous versions, _inline is a synonym for __inline.We can declare a function _inline in following manner:-

__inline void congratulate(int score);


(11)inline:-It has the same woak as __inline .The main difference is that it is only available in C++.The inline keyword used as following manner:-

inline int add(int i, int j) { return i + j; }

(12)mutable:-This keyword can only be applied to non-static and non-const data members of a class. If a data member is declared mutable, then it is legal to assign a value to this data member from a const member function.

mutable member-variable-declaration;

(13)thread_local:-The variable is allocated when the thread begins and deallocated when the thread ends. Each thread has its own instance of the variable. Only variables declared thread_local have this storage duration. thread_local can only be declared for global variables, plus those declared with static or extern.It is declared as following:-


 thread_local unsigned int rage = 1


Thursday 21 March 2013

Creating and using a Dll from Empty project

It is very important to know that how cane we create a Dll from an empty project and how can we use it.

Creating a library:-

We can create it by following steps:-

1)Create an empty project into the visual studio.


2)We need the function with the following syantax.


#include<iostream>
#include <cstdio> // instead of <stdio.h>
#include <cstdlib> // instead of <stdlib.h>
 #include <conio.h> //-- do not use

#include <cstring> // instead of <string.h>
using namespace std;

//C++ style header decoration in the dll
  __declspec(dllexport)  int __stdcall add(int a ,int b )
{
 return a+b;
}
//c style header declartion in the dll
 extern "C"  __declspec(dllexport) int  _stdcall sub(int a ,int b )
{
 return a-b;
}
//C++ style header decoration in the dll
  __declspec(dllexport)int _cdecl mul(int a ,int b )
{
 return a*b;
}
//c style header declartion in the dll
extern "C" __declspec(dllexport)int  _cdecl divide(int a ,int b )
{
 return a/b;
}


3)Now, we need to follow these steps:-
 project properties -> general->project defaults ->configuration type->choose dynamic library(.dll)


4)Then we need to build it .After building it the .lib file is generated .

(5)Now we Can use these functions into other files by including .lib file and header files into that project.

Using the created library: -.We can use the created library by adding this .lib file to that project in which we want to use it.We need to create a new project and call the functions in that project after adding the library.We need to write following code for using this library.


#include<iostream>
using namespace std;

//C++ style header decoration in the dll
int __stdcall add(int a ,int b );

//C style header declartion in the dll
extern "C" int  _stdcall sub(int a ,int b );

//C++ style header decoration in the dll
int _cdecl mul(int a ,int b );

//C style header declartion in the dll
extern "C" int  _cdecl divide(int a ,int b );

void main()
{
 cout<<add(3,4);
 cout<<sub(4,3);
 cout<<mul(3,4);
 cout<<divide(4,2);
}



There are two methods to adding the .lib fie:-

1)We need to go to add->existing item->choose .lib file
2)
(a)In the project property  Go to  VC++ Directories   .In librery Directories add the  full path where the .lib is placed.



(b)n the linker -->Input-->additional Dependencies -->add the .lib file of the dll generated.



Now we can easily use the library by adding any of these two methods.

*.lib function is required to build the function and .dll and .lib both required for the execution of the program.

Wednesday 20 March 2013

__declspec

__declspec is a storage specifier which specifies that an  instance of a given type is to be stored with a Microsoft specific storage -class attribute listed below:-


  1.  align( # )
  2. allocate(" segname ")
  3. appdomain
  4. deprecated
  5. dllimport
  6. dllexport
  7. jitintrinsic
  8. naked
  9. noalias
  10. noinline
  11. noreturn
  12. nothrow
  13. novtable
  14. process
  15. property( {get=get_func_name|,put=put_func_name})
  16. restrict
  17. safebuffers
  18. selectany
  19. thread
  20. uuid(" ComObjectGUID ") 

(1)align (#):-We can use __declspec (align(#)) to precisely control the alignment of user-defined data (for example ,static allocations or automatic data in a function).
Ex:-


__declspec( align( # ) ) declarator

(2)alllocate ("segname") declarator:-The allocate declaration specifier names a data segment in which the data item will be allocated .
Ex:-
__declspec(allocate("segname")) declarator

(3)appdomain:-_declspec(appdomain) is only valid when one of the /clr  compiler option is used .Only a global variable ,static member variable or static local variable can be marked with _declspec(appdomain ).It is an error to apply _declspec(appdomain ) to static members of managed types because they always have this behaviour.
(4)deprecated:-  The deprecated specify particular forms of functions overload as deprecated ,whereas the pragma form applies to all overload forms of a function name.The deprecated declaration specify a message that will display at compile time.The text of message can be from a macro.Macros can be marked as deprecated with the deprecated pragma.
(5)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;
(6)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();
(7)jitintrinsic:-It marks the function as significant to the 64-bit common language runtime.This is used on certain functions in microsoft -provided library .
_decspec (intrinsic)

(8)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 ) {}

(9)noalias:-noalias means that a function call does not modify or reference visible globle state and only modifies the memory pointed to directly by pointer parameters .If a function is a annonated as noalias ,the optimizer can assume that in addition to the parameter themselves,only first-level indirections of pointer parameter are referenced or modified inside the function .

(10)noinline:-_declspec(noinline) tells the compiler to never inline a particular member function .If a function is marked noinline ,the calling function will be smaller and thus ,itself a candidate for compiler inlining .

(11)noreturn:-It tells the compiler that a function does not return .As a consequence ,the compiler knows that the code following a call to a _declspec (no return function) is unreachable .
(12)nothrow:-It can be used in declaration of functions.It tells the compiler that the declared function and the the functions it calls never throw an exception . 

return-type __declspec(nothrow) [call-convention] function-name ([argument-list])

(13)novtable:-This form of _decspec can be applied to any class declaration ,but should only be applied to pure interface classes,that is ,classes that will never be instantiated on their own .If we attempt to instantiate a  class marked with novtable  and then access a class member ,we will receive an access violation.

(14)  process:-It specifies that we managed application process should have a single copy of a particular global variable ,static member variable or static local variable shared  across all application domain in the process .Only a global variable,static member variable or static local variable of native type can be marked with __declspec(process).

(15)property:-This attribute can be applied to non-static "virtual data members" in a class or structure definition.The compiler treats these "virtual data members " as data members by changing their references into function calls.



__declspec( property( get=get_func_name ) ) declarator
__declspec( property( put=put_func_name ) ) declarator
__declspec( property( get=get_func_name, put=put_func_name ) ) declarator


(16)restrict:-It is applied to a function declaration or definition that returns a pointer type and tells the compiler that the function returns an object that will not be aliased with any other pointer .



__declspec(restrict) return_type f();

(17)safebuffers:-safebuffers tells the compiler not to insert buffer overrun security checks for a function.
 An expert manual code review or external analysis might determine that a function safe from a buffer overrun.In that case we  can suppress security checks for a function by applying the _declspec (safebuffer)
keyword to the function declaration .

__declspec(safebuffers)

(18)selectany:-It tells the compiler that the declared global data item (variable or object )pick any packaged function.selectany can only be applied to the actual initialization of global data items that are externally visible.

__declspec( selectany ) declarator

(19)thread:-The thread extended storage class modifier is used to declare a thread local variable.It is used with _declspec(thread) declarator .We can apply the thread  attribute only to data declaration and definitions and classes do not have member functions ,thread cannot be used on function declaration or function definitions.


___declspec( thread ) declarator

(20)uuid:-The compiler attaches a guide to a class or structure declare or defined with the uuid attribute.The uuid takes a string as its argument .This string names a GUID in normal registry format with or without the ()delimeters.

struct __declspec(uuid("00000000-0000-0000-c000-000000000046")) IUnknown;
struct __declspec(uuid("{00020400-0000-0000-c000-000000000046}")) IDispatch; 


Tuesday 19 March 2013

Keywords in C/C++(Microsoft Specific)

There are some microsoft specific keywords used in C/C++.We need to know about their characteristic which are following:-

(1)_asm:-The _asm keyword invokes the inline assembler can appear wherever a C or C++ statement is legal .It cannot appear by itself.It must be followed by an assembly instruction ,a group of instructions enclosed in braces or at the very least an empty pair of braces .

Ex:-

__asm {
       mov al, 2
       mov dx, 0xD007
       out dx, al 
       } 
(2)dllimport:-It is used to import function ,data from the dll.It is used with _declspec keyword.

(3)_int8:-It is a integer of 8-bit.It is synonymous to char.

(4) 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 ) {}



(5)_based:-_based keyword allows us to declare pointer based on pointers .The _based keyword has limited uses 32-bit and 64-bit target compilations.
Ex:-



type __based( base ) declarator


(6)_except:-It is used in a try-except statement._except is used as an exception handler.

(7)_int16:-It is a 16 bit integer and synonymous to  the short.

(8)_stdcall:-stdcall calling convention is used to call Win32 API functions .In this calling convention callee
cleans the stack ,so the compiler makes vararg functions _cdecl .Functions that uses this calling convention require a function prototype .It pushes parametes on the stack in reverse order means right to left .Function declared  using with the _stdcall modifier returns values the same way as function declare using _cdecl.
Ex:-

return-type __stdcall function-name[(argument-list)]

(9)_cdecl:-decl is the default calling convention in C/C++.In this calling convention the stack is cleaned up by the caller .It creates larger executable than _stdcall because it requires each function call to include stack cleanup code .It pushes parameters on the stack in reverse order means right to left.There is no case translation performed in this calling convention.Underscore caracter(_) is used as prefix to names ,except when exporting _cdecl functions that use C linkage .

Ex:-

int __cdecl system(const char *);

(10)_fastcall:-It specifies that arguments to functions are to be passed in registers ,when possible.Stack clean up is done by callee function .It pushes parameters in reverse order means right to left.There is no case translation is performed in this calling convention.
Ex:-
void FASTCALL DeleteAggrWrapper(void* pWrapper);

(11)_int32:-_int32 is used as 32 bit integer.It is synonymous to type int.
(12)thread:-The thread extended storage class modifier is used to declare a    thread local variable.It is used with _declspec(thread) declarator .
(13)_declspec:-It is a storage class modifier  used with many extended attribute like dllimport and dllexport.
(14)_finally:-_finally is used in try-finally statements.The try-finally statement is a microsoft extension to the C and C++ language that enables target applications to guarantee execution of cleanup code when execution of block of code is interrupted .
(15)_int64:-_int64 is a integer of 64 bit.
(16)_try:-A _try keyword is used in _try-_except,_try-catch,_try-_finally statement to enclose one or more statements that might throw an exception.
(17)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.

(18)_inline:-The _inline specifier instructs the compiler to insert a copy of the function body into each place the function is called .
(19) __leave:-The __leave keyword is valid only within the gaurded section of a try-finally statement and its effect is to jump to the end of the guarded section.   




Keywords in C/C++(Basic)

Keywords are the words whose meaning has already explained to the C compiler.The keywords cannot be
used as variable names because we do it means we are trying to change the meaning to the keyword which is not allowed. There are various keywords used in C/C++.We need to know about their behaviour  :-

(1)auto:-auto is a storage class which is default storage class to the variable declared in a block.The scope and lifetime of the variables is in the block.

(2) double:- double keyword is used for the declaration of large decimal nos .It is of 8 bytes normally.

(3)int:- int is a keyword used for declaration of integer type of variable.It is  of  4 bytes normally.

(4)struct:-struct is used for the declaration of structure.

(5)break:- break is used for terminate the loop.

(6)else:-else keyword is always used with if .It works when if condition is not satisfied.

(7)long:-long keyword is a modifier which is used for used a large integer in program.

(8)switch:-switch is used for multy condition  statements.There are many cases used in switch .Each case have different task.

(9)case:-case keyword is used in switch statements.

(10)enum:-enum keyword is used for declare a user-defined enumeration which consist of a set of named constants called the enumerator list .By defualt the enumerator has the value zero and the value of each successive enumerator is increased by 1.

(11)register :-  register is also a keyword used for storage class .The lifetime and scope of the variable of this type is in the block where is declared.

(12)typedef:-The purpose of this keyword is to assign alternatives names to existing types.

(13)char:-char is a keyword used for a 1-byte datatype.

(14)extern:-extern is a keyword used for storage class.The lifetime of this type storage class is in  whole
program and scope of the variable is in the block or compilation unit.

(15)return:-return keyword is used for return a variable from a function to the callee.

(16)union:-union is a keyword used for the declaration of an union.

(17)const:- const is a keyword used to declare a qualifier  which is initialize once and value cannot modified in program.

(18)float:-float keyword is also used to declare a datatype which is used to store decimal values in it.

(19)short :- short is a keyword used to denote a modifier which is used with integer.

(20)unsigned:-unsigned keyword is used to denote a modifier which is used with datatypes like int and char to confirm that the value stored in that datatypes must be unsigned .

(21)continue:-continue take the control into the beginning of the loop.

(22)for:-for is used to decision control statement .It has the three values in it:initialization,condition and increment/decrement.

(23)signed :-signed keyword is used for declare a datatype signed it means the datatype can have positive as well as negative value.

(24)void:-void is keyword that declares that a function does not have any return type.

(25)default:-default kayword is used in switch statement when does not give any specific case then it is automatically executed.

(26)goto:-goto keyword is used to take control at any specific line.

(27)sizeof:-sizeof keyword is used to know the size of any data type ,structure and arrays .

(28)volatile:-volatile keyword is used to declare an integer a special type of integer whose value can be change by concurrently executing thread or operating system.

(29)do:-do keyword is used in do-while statements .It runs the loop untill the condition in while is satisfied.

(30)if:-if is conditional statement which is used for executing that part of program in special condition.

(31)static:-static keyword also used to declare a storage class specifier which has the lifetime during the program and scope in block or compilation unit.

(32)while:-while is a keyword used for a conditional statement in which loop is repeat until while condition is specified.

(33)restrict:- restrict is a keyword used to declare a special type of pointer which point to that memory chunk which can not be point by anything else. 

Saturday 16 March 2013

Calling conventions in C/C++

There are following five calling conventions used in C/C++:-
1)_cdecl
2)_clrcall
3)_stdcall
4)_fastcall
5)_thiscall

1)_cdecl:-_cdecl is the default calling convention in C/C++.In this calling convention the stack is cleaned up by the caller .It creates larger executable than _stdcall because it requires each function call to include stack cleanup code .It pushes parameters on the stack in reverse order means right to left.There is no case translation performed in this calling convention.Underscore caracter(_) is used as prefix to names ,except when exporting _cdecl functions that use C linkage .

2)_clrcall:- _clrcall is used for all virtual function which only be called from managed code .This calling convention can not be used for function that will be called from native code.It improves performance in the case of virtual functions.The load parameters onto CLR expression stack in left to right order.When a function is declared with _clrcall ,code will generated when needed for example ,when function is called.

3) _stdcall:-_stdcall calling convention is used to call Win32 API functions .In this calling convention callee
cleans the stack ,so the compiler makes vararg functions _cdecl .Functions that uses this calling convention require a function prototype .It pushes parametes on the stack in reverse order means right to left .Function declared  using with the _stdcall modifier returns values the same way as function declare using _cdecl.

4)_fastcall:-It specifies that arguments to functions are to be passed in registers ,when possible.Stack clean up is done by callee function .It pushes parameters in reverse order means right to left.There is no case translation is performed in this calling convention.

5)_thiscall:-This is used on member functions and  it is the default calling convention used by C++ member functions that do not use variable arguments .In this calling convention the callee cleans the stack which is impossible for vararg functions.The arguments are pushed on stack from right to left .On reason to use _thiscall is in classes whose member functions use _clrcall by default .In that case we can use _thiscall to make individual member function callable from native code .

We can easily seen their characteristic from following table:-

Friday 15 March 2013

Digraph ,trigraph and escape sequences

In computer programming ,digraph and trigraphs are sequences of two and three characters respectively,appearing in source code ,which a programming language specification requires an implementation of that language to treat as if they where one other character .Digraph and trigraphs used because keyboard may not have keys to cover the entire character set of the language ,input of special characters may be difficult,text editors may reserve some characters for special use and so on .Trigraphs might also be used for some EBCDIC code pages that lack { and } type characters.Trigraphs are not commonly encountered outside compiler test suites.Some compiler support an option to turn recognition of trigraphs off or disable trigraphs by default and require an option to turn them on.Some can issue warning when they encounter trigraphs in source files.


The digraph characters are:

%: or %% #                   number sign
<: [                                   left bracket
:> ]                                   right bracket
<% {                                   left brace
%> }                                   right brace
%:%: or %%%% ##   preprocessor macro concatenation operator


Trigraph
Single           character                             capription
??=            #                                     pound sign
??(                 [                                     left bracket
??)                 ]                                     right bracket
??<              {                                     left brace
??>                 }                                     right brace
??/                  \                                     backslash
??'                 ^                                     caret
??!                 |                                     vertical bar
??-             ~                                     tilde



Escape Sequences :-A escape sequence is a series of characters used to change the state of computers and their attached peripheral devices .These are also known as control sequence reflecting their use in device control .Some control sequences are special characters that always have the same meaning.Escape sequence   uses an escape character to change the meaning of the characters which follow it ,meaning that the characters   can be interpreted as a command to be executed rather than as data.
                                            Escape sequence are commonly used when a computer and a peripheral have only a single channel through which to send information back and forth.Normally we use following escape sequences which are written with their meaning:
  \\ Literal backslash
\"                  Double quote
\' Single quote
\n                 Newline (line feed)
\r Carriage return
\b Backspace
\t Horizontal tab
\f Form feed
\a Alert (bell)
\v Vertical tab
\? Question mark (used to escape trigraphs)
\nnn Character with octal value nnn
\xhh Character with hexadecimal value hh

Ellipsis(...) Symbol in C

A different type of argument passing used in C which we is not very popular but very important to know.It is also used by printf and scanf function because we can pass variable no of variables in printf and scanf.We can see how we use this elipsis symbol in our program.So here is the snapshot of my program:

The output of this program will be 11 and 18 respectively.


Wednesday 13 March 2013

Character set encoding

Character set:-When we write a program, we express source files as text lines containing characters from the source character set.When a program executes in the target environment ,it uses characters from the target character set.These character sets are related ,but need not have the same encoding or all the same members .
               Every character set contains  a distinct code value for each character in the basic C character set.A character set can also contain additional characters with other code values .For example:

  •    The character constant 'x' becomes the value of the code for the character corresponding to x in the target character set.
  • The string literal "xyz" becomes a sequence of character constants stored in successive bytes of memory,followed by a byte containing  the value zero{'x','y','z','\0'}. 
Character encoding:-A character encoding system consists of a code that pairs each character from a given repertoire with something else such as bit pattern,sequence of natural numbers,octets or electrical pulses, in order to facilitate the transmission of data through telecommunication networks or for data storage .Common example of character encoding systems include Morse code,the Baudot code ,Ascii and Unicode.
Here are some important terms used in character set encoding :-

ASCII:-Ascii stands for American standard code for information interchange .It is a character encoding scheme originally based on English alphabet.Ascii codes represent text in computers,communication equipment and other devices that uses text.Most modern character encoding scheme is based on Ascii though they support many additional characters.Ascii developed from telegraphic codes.Its first commercial use was a seven-bit teleprinter code.Ascii includes definitions for  128 characters: 33 are non printing control character that affects how text and space are processed and 95 printable chars including space which is considered an invisible graphics.Extended ASCII comprises 256 code point in the range 0(hex) to ff(hex)

EBCDIC:-EBCDIC stands for extended binary coded decimal interchange code is an 8-bit chatracter encoding use mainly on IBM mainframe  and IBM midrange computer operating system.It is developed before ASCII. EBCDIC has no technical advantage compared to ASCII based webpages .

Unicode:-Unicode is a computer industry standard for the consistent encoding,representation and handling of text expressed .It is a worldwide character encoding standard that provides a unique number to represent each character used in modern computing ,including technical symbols and special characters used in publishing.



UNICODE
Universal character name                                   ISO/IEC 10646 short name
where N is a hexadecimal digit
\UNNNNNNNN                                                   NNNNNNNN
\uNNNN 0000NNNN

. UTF literals
Syntax                                                            Explanation
u'character'                                                   Denotes a UTF-16 character.
u"character-sequence"                                Denotes an array of UTF-16 characters.
U'character' Denotes a UTF-32 character.
U"character-sequence"                               Denotes an array of UTF-32 characters.


examples:

u'\u1234'

u"\u1234\u8189"

U'\U12345678'

U"\U12345678\U43332233"




                 Unicode comprises 1,114,112 code points in the range 0(hex) to 10FFFF(hex) code points in the range.The Unicode code space is divided into seventeen planes(the basic multilingual plane and 16 supplementary planes),each with 65,536=(2^26) code points.Thus the total size of the Unicode code spaces 17*65,536=1,114,112.  Unicode is required by modern standard such as XML and java scripts.It is supported by many operating systems all modern browsers.It has two mapping metods:-

1)UTF:-It stands for unicode transformation format.For UTF encoding the number in the names of encoding indicate the no of bits in one code value.
  a)UTF-8:-UTF-8 is a variable width encoding that can represent every character in  the Unicode character set.It was designed for backward compatibility with ASCII and to avoid the complications of endiannes and byte order marks in UTF-16 and  UTF-32.UTF-8 has become dominant character encoding for the world wide web accounting for more than half of all webpages.UTF-8 is also increasingly  being used as the the default  character encoding in operating systems, programming language,APIs and software application.
 b)UTF-16:-   UTF-16 (16-bit unicode transformation format)is a character encoding for encoding 1,112,064 numbers in the Unicode color space 0 to 0x10FFFF.It produces a variable-length result either one or two 16-bit code units per code-unit.
c)UTF-32:-UTf-32 is a protocol to encode Unicode characters that uses exactly 32 bits per Unicode code point .All other Unicode information formats use variable -length encodings.The main advantage of UTF-32 versus variable-length encodings ,is that unicode code points are directly indexable .
d)UTF-EBCDIC:-UTF-EBCDIC  is a character encoding used to represent Unicode characters .It is meant to be EBCDIC -friendly .

2)UCS:-The Universal character set (UCS) is standard set of characters upon which many character encoding are based.The UCS contains  one hundred thousand abstract characters,each identified by an unambiguous name and an integer number called its endpionts.Characters (letters,numbers ,symbol, ideograms ,logograms etc.) from the many languages ,scripts and traditions of the world are represented in the UCS with unique cods points .It has two forms:-

a)UCS-2:-UCS-2 is similar to the UTF-16.

b)UCS-4:-It is similar to the UTF-32.

Multibyte Character Encoding:-Multibyte character encoding uses varying number of bytes to encode different characters.Multibyte encodings are usually the result of a need to increase the number of characters which can be encoded without  backward compatibilty with an existing constraint .

Wide-character:- A wide character is a computer character datatype that generally has a size greater than the traditional 8-bit character .The increase datatype size allows for the use of larger codec character sets.A wide character refers to the size of the datatype in memory .It does not state how each value in a character
set is defined .Those values are instead defined using characters sets with UCS and Unicode simply being two common character sets that contain more characters than an 8-bit value would allow.

We need to know answers of some questions which are necessary to know us:-

1) What is the default value of character encoding in visual studio.?
Ans:-character set-Use Multi-Byte Character Set
2)What are the possible values of character encoding in VS ?
Ans:-1)Use Multi-Byte Character Set
        2)Not Set
        3)Use Unicode Character Set
3)How can you change this value in VS?
Ans:-We can change this value with following procedure:-
        a)Go to the project properties in visual studio.
        b)There is a option for character set in project defaults where "Use Multi-Byte Character Set"
           is already selected .We can change by clicking the drop down button at left side.
        c) From there we can choose any option among all possible values .
        d)Then Click Ok or Apply to set.

(4)What is the code unit for each set?
Ans:-Here is the code unit for each character set:-
1)US-ASCII       -  7bits
2)UTF-8             - 8bits
3)EBCDIC         - 8bits
4)UTF-16           -16 bits
5)UTF-32           -32 bits