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