## Tuesday, December 18, 2007

### 2d lines intersection point & Linear equations

Do you remember the linear equations studied ? and methods to solve linear equations ?  may be some of us remember it.

We know every line can be represented by a linear equation of the form Ax+by  =c . or in the point slope form y = mx + c.so if you have two lines in the graph  ( or in ur game) you can find the intersecting point by solving these equations. You can find the intersecting point by solving these equations.

For example if you have two lines corresponding to , y = 2x,  and y = 0x+ 3 ( horizontal line ) so certainly these lines will intersect. .slopes are 2 and 0 respectily. so by solving these equations 2x-y =0 , and 0x + y = 3, we will get x = 3/2 and y = 3.

So what is the best method for solving linear equations using computers ? There are methods like

1. Linear compostion (normal equation solving , by adding or subtracting 2 equations)
2. gauss elimination method ( using matrixes. i think everybody knows it , no need for explanation. ).
3. Cramer's Rule. ( creating the cofactor matrix and finding determinent , andby dividing with determinent).

So which is the best ? I think gauss elimination is best. Because when the matrix diamension becomes bigger , cramer's method even takes days to find the answer.But Gauss elimination method won't .

## Wednesday, December 12, 2007

### Reducing Heap Fragmentation with Low Fragment Heap Featuer

Today most pc have enough memory . But there is still chance to occur fragmentation by continuously allocating and freeing small chunk of memory.

Windows Xp , Windows Server 2003 has a new feature called Low fragment heap(LFH).
If you enable this when creating heap , this can reduce heap fragmentation.The LFH has a predefines set of memory chunks of different sizes. it called this chunk as buckets , so when we request for a a few bytes , the LFH returns the bucket of smallest size.

The LFH option can be enable by the API HeapSetInformation. For example it may look like
long HeapFragValue = 2;

HeapSetInformation( GetProcessHeap(),HeapCompatibilityInformation,HeapFragValue,sizeof(HeapFragValue) );

2 indicates the information is about LFH.
This feature is very useful. Otherwise you may need to write your own allocators and handle the memory pool.
When writing allocator we need to think about the page size , number of page faults etc. and certainly it takes some time.   So if you are in hurry try the LFH option. :)

## Thursday, November 15, 2007

### How to make application Faster C++/C

Following small optimaization can make applications more faster . I think.

1.Make small functions  as inline functions.

2. If you are  using variable to hold constant data , make in const.
like int i = MAX_VAL; can be changed to const int i = MAX_VAL

3.Creating simple expressions
some exmaples like belowif(i == MAX_VAL) return 1;
else return 0 ;
can be replaced with return ( i==MAX_VAL);

another one if( i ==0 ) return nVal; else returrn 0; can be replaced with  return (i==0) ?nVal : 10   Ternary operator is fast than if else.

4.When function calling don't pass long arrays . Use pointers or reference.

5.For copying array use api , like CopyMEmory , memcpy.
(They uses asm codes to get the tas done)

6. similarly for initializing memset also can be used .

7. When increamenting class objects uses ++obj , rather than obj++.
(because obj++ might create  temporary objects).

8. Too much object oriented approch will also affect speed.

9. when one function called ,  It is wise to return first if any argument is invalid , rather than do it later.
like
fun()
{
if(param == 0 || param1 = 0 || n!=V) return 0;
return 1;
}

10. Allocating memory several times wil cause fragmentation, so allocate a buffer pool first.

11. Similarly try to avoid creating mutiple files in Hard disk .It will also cause fragmentation.
Try to do the work with one file, otherwise think about databases.

12.  Use int , as loop couner etc. Because int size same as the processor register size, so it is fast than others.

13.  Exception catching is expensive , it will cause application slower , and will increase the size of  EXE.

Do if you are not using exception handleres , you can turn it off in compiler settings
Also avoid putting exception handling inside repeatedlycalling functions .
Put exception handling on in the main parts of program.

14. you can use __fastcall to make functions calls faster , it wil try to put arguments in registers._cdecl will increase the size of EXE.

15. Don't load all DLLs on application loading . Most of the cases applications slowing down due to these reasons.
DLL as name implies is for dynamic loading.

16. Most important , Before copying code from somwhere Understand it :)

## Monday, October 29, 2007

### C,C++ Geek's way to access array/ pointer elements.

After a short gap , i am back. This is post is from old memories. I don't know how many people know this ?
I don't want to explain much. Look the following codes

int nArCounts[3]   = {30,20,50};

Normally people accessing array element like nArCounts[i].

It is also possible to access it like this i[nArcounts] ,Both are converted to nArcounts + i .
Thats all , But if a guy don't know this , when he/she sees these type of notations he will get mad. I am sure.

## Friday, September 21, 2007

### STL vector and Some memory concerns.

I know STL vector is smart & very efficient . But when we using it lacks some memory deallocation functions other than destructor.
This is depending according to the version of Visual studio you are using . If you are using VS7 , the vector::clear() will remove all memory used by the vector. Otherwise , i mean if the compiler is VS2005 , you are in trouble. The vector hasn't any functions to release all memory used by it , except ~vector() (destructor).

Consider the following situations using VS2005

vector <int> myVec;
for(int i = 0 ; i < 10000; i++) myVec.push_back(i);
// ....some  codes.......

myVec.erase(myVec.begin()+1,myVec.end()); /*  removed all elements except the first.
But memory still allocated , because vector
reserved the memory for future allocations.*/

erase will mearly just removes  elements from the vector and calls destructor (->~_ty()). So still the memory is not deallocated(call myVec.capacity() to see the allocated bytes) .. What to do ? if you want to free up memory (Ofcourse u can delete , the last way).
One trick is to copy the contents to a new vector and again recopy it to the original vector , see below. Here the new vector(copy) will takes only the actual memory (it can be verifed using vector::capacity() ). During the recopy to original vector (myVec = copy) , the unwated memory is deleted.

Like

{

vector<int> copy  = myVec;
myVec  = copy.

}

So now the memory will be delted.. Ofcourse it makes some perfomance imacpt due to copy operation . But In some cases it can save a lot of memory . It depends upon the type of applcation.

Note : I have checked this only with Visaul Studio 7 , 8's  implementaion of STL.

## Thursday, September 20, 2007

### GetOpenFileName() And Some Deep crashes..

I think most of all windows programmers are familiar with GetOpenFileName() API (in MFC CFileDialog class).This api popups a open file dialog letting users to select the file they want.
Okay , I am going into the matter.
1. click open from menu , now you can see open file dialog. Navigate to Desktop
2  move the mouse pointer around some file till tool tip visible.
3. Now cancel the dialog (press cancel or ESC)
4. Try to repeat the same thing (make sure again you go to desktop) , you will be awaited with a crash. Notepad disappears.

Interestingly This happens only with Desktop. I don't know why . So you might ask me how it mess up with the GetOpenFileName. Yes it relates , try calling GetOpenFileName in win32 App (not MFC). You can see the same behavior , your application crashes..

This is Bug in windows XP ( Service pack??? , any oher Version ??? ) .. i don't about any other versions.
If you debug the application you can't see any stack trace . This also happens with the GetSaveFileName api also.
For calling GetOpenFileName you need initialize COM , by calling CoInitialize(0) in the first of the program and call CoUnitinialize in the end of the program. Then it should work. The interesting thing is that in MSDN there is no information about this.

If you call like this as show below , still you can expect the crash.
CoInitialize(0);
GetOpenFileName();
CoUnitialize()

I don't know the exact reason . But my guess is that the GetOpenFileName() / SaveFileName() creats 4 threads .Even you close the dialog these thread exists ,  and these threads might call some com calls , after your CoUnitialize() . That may cause some problems. The most important this is that , There is a chance to crash every application ,  that uses GetOpenOpenFile/GetSaveFile dialog (and not initializing COM) . Seriously..

## Sunday, August 26, 2007

### Type casting using Assembly code win32

We know that C++ will not allows assiging variable if they are on different typee. In That situations type casting is needed..But In some cases we can't use the c++ inbuilt type casting system as well as C style casting also..

I am taking an exmaple of CreateThread thread proc function.(Beacuse many people uses static functions as the

For example if you look the function CreateThread API,the thread proc type is
DWORD WINAPI ThreadProc(void *lParam)
{

}

So this insist you to create some global functions or static functions.

Hence you can't pass your class member functions to CreateThread. So usually people will create some static functions and pass that function to CreateThread.And from inside that static function the appropriate class function is called..

This is fine. But using a littile asm code this can be avoided.
For example CCoffe is your class, and the MakeCoffe function we want to pass to CreateThread.  This can be done as below.

//sample codes
class CCoffe
{
DWORD MakeCoffe(void *lParam)
{
return 0;
}
}

//Initialization  function.
CCoffe::Init()
{
//temp is a function pointer of ThreadProc Type.
DWORD (WINAPI*temp)(void*lp);
__asm //Here we can pass any  address  to temp.
{

mov EAX,CCoffe::MakeCoffe
mov temp,EAX
}
//Call CreateThread with temp
DWORD  out;
}

The Point is we can pass any address to temp,using asm block.Passing wrong function addresses
may cause invalid stack structure,Might result in a crash.Hopes next time you will avoid static functions..

Note: I Don't know is this a good practice or not, If you have any opinion please let me know..

## Friday, August 24, 2007

### NULL pointer and Some thoughts C++

Its me again , now came with a NULL pointer in hand... You may think what so special about NULL pointer , right ? .

it is very special . for example even if multiply two NULL pointers ,you will get a the result as a NULL pointer.. is it interesting ? .. :) I was just joking..

I wrote this beacause mostly people checks in destructor something like this

if(p) delete p;

This is not needed , you can just avoid that checking, because delete NULL , will not cause any probles.
so if you have more pointers in your class to delete , avoid that checking is too good to see.

I think Now it is good to mention about this function  IsBadWritePtr . This function can be used to check
whether one address is good to write. In MFC there is function AfxIsValidAddress which will call this function to check.

The next thing about NULL pointer is that , You can still call member functions with null pointer, Like

CCLemon *p = NULL;

p->Drink() ;

Still this will works . but only one condition , Drink should not access any member variables of class CCLemon , and Drink shouldn't be a virtual function. If Drink is a virtual function result is Bhooommm!!!

## Monday, August 20, 2007

### Quick way to disable global keys (like ALT + TAB )

Some times it needed to disable the functonality of the global keys like ALT + TAB ,CTRL + ESC . For example when playing some games , pressing ALT + TAB will not cause to switch the tasks. Personaly i don't like this ,but programmers do these ,otherwise they might needed to handle something more..

So if you want to do these , One way is to use Hooks , using SetWindowHookEx api. But there is much simpler way to do this , using hot keys. There is function named RegisterHotKey , this will define a system wide hot key. So the effect is same as Hook.

After defining a hotkey ,when the hotkey is pressed by the user WM_HOTKEY message will be posted to message queue of that window .

So if you want to disable ALT+TAB , install a hotkey using
RegisterHotKey(hwnd,id,MOD_ALT,VK_TAB).

Done!!!! . Very simple than hooks.you can also handle the WM_HOTKEY message to do your own tasks..

## Thursday, August 9, 2007

### operator= & Inheritance c++

One interesting thing about operator = is that it can't be inherited.. So even if your base class has operator=  , no use for derived class. For example CString has operator= , but if you derive a class from CString you will not get = operator functionality in your derived class.

But there is a neat trick that will explicitly put this operator= in to the derived class. Here it is

class CString
{
public :
CString& operator=(char *)
{
// some codes
return *this;
}
};
class CMyString : public CString
{
public:
//We explicitly inserted the operator.
using CString::operator=;
};

Now CMyString gets the operator from CString.

## Wednesday, August 8, 2007

### Checking the presence of Virtual table in a class c++

The Last day when i am debugging one program , i saw the __vfptr symbol in VC++ . This represents the the vtable of a class. When you debuging your program try obj1.__vfptr in watch window. It will show the virtual functions of that class.

On that time I thought about writing such a function to check the vtable presence in a class , it is not a bad Idea..

So This post is about checking the whether a class contains virtual function or not. I want to write a function like IsVTablePresent(MYclass) , the function will return true if there is a vtable ,Otherwise false.

I don't know is this type of functins are really useful or not , but i think these are really smart .

Here is my solution using templates , It is very easy.

template <typename T>
class tDervVir : public T
{
virtual void VirtualFun(){} //dummy
};

template <typename T>
class tDervNormal : public T
{
// No virtual functions inside.
};

template <typename T>
class VFinder
{
public :
int IsVirtualContains() //this is our function
{

tDervNormal<T> obj1;
tDervVir<T>    obj2;
return sizeof(obj1) == sizeof(obj2);
}

};

By using the above classes it can be done. For example consider a class CSample as the class for testing.

class CSample
{
virtual void PoorMan(){}
};

We can check CSample as the following way

VFinder<CSample> tester;
(tester.IsVirtualContains() ? cout << "Virtual present" : cout << "Virtual not present" ;

Thats all for now..

## Tuesday, August 7, 2007

### Calling class Constructor C++

Some times we may think it would be nice , if we can call the constructor again for some initialization stuff (Normally constructor does the initialization job).  It is not possible to call the constructor of a class explicitly. Only way is to call is new operator. So here is that.

It is achived using placement new technique. it is very easy. For example if you have class CAlgoritham and the constructor of CAlgoritham does most of the initialization works. So after some processing you may want to  reset it to the old state (may be depnds on the algoritham). You have already wrote the initialization codes in constructor , but it is not possible to call constructor again. So we can use placement new. Here it is

CAlgoritham alg; //member variables Initialized already
alg.DoProces113();

new (&alg)CAlgoritham(); //this will call consructor again.But it  will not create a new memory (since we are giving memory location).

The statement new (&alg)CAlgoritham() is equal to CAlgoritham::CAlgoritham();

I like this kinda of things. Hopes you too.

## Saturday, August 4, 2007

### STL Vector in VS 2005 ( when porting from 2003 or < )

In VS 2005 they changed almost all C runtime libraries and STL classes for adding security practices. Here is one information about the vector class in STL. So if you have any code written in 2003 , and if you port that to VS2005 be careful.

In 2003 the following vector operations will work , like
vector<int> SomeInts;
SomeInte.push_back(0);
SomeInte.push_back(1);
SomeInte.push_back(2);

vector<int>::iterator it = SomeInts.Begin(); // Now it points to 0
++it;                                       // Now it points to 1
SomeInts.erase(it);                         // We are deleting the 1 from list
--it                                        // We want to move to 0 again.

and if you again ++it you will get 2. because we just deleted 1 from the vector. Ok, everything fine.
But In VS 2005 , the red marked line above(--it) cause to a crash!!! . Because the iterator it is invalid so --it is also invalid.

SO to correct that error best way is like this

vector<int> SomeInts;
SomeInte.push_back(0);
SomeInte.push_back(1);
SomeInte.push_back(2);
vector<int>::iterator it = SomeInts.Begin();   // Now it points to 0
++it;                                          // Now it points to 1
it = SomeInts.erase(it);                       // We are deleting the 1 from list
--it                                           // Now it points to 0

[ The last day , my friend told me he is getting a strange error in VS2005 , not in 2003, it was this problem. ]

## Thursday, August 2, 2007

### Calling Destructor & Virtual table c++

IF you really know how virtual functions work,it is really fun. Here is such an example(for fun i wrote a function fun  )

class base
{
public :
virtual void fun()
{
cout <"base fun";
}
~base(){}
};
class deriv: public base
{
void fun()
{
cout << "deriv fun";
}
~ deriv(){}
};

very simple two classes..
We know virtual funtions are initlaized in constructor and removed to their old base versions in the destructor.

Here is One more proof .
Try these if you are interested , otherwise go to www.youtube.com

base *p = new deiv();
p->fun();
p->~base();
p->fun();

the outputs will be first

deriv fun and
base fun

Because when we call p->~base() it will replaces the virtual pointer with the base version of fun. Thats why the base::fun get called.
We can't call constructor explicity as we did with destructor.
Ok , I am stopping now.

## Tuesday, July 31, 2007

### RichEdit Common Mistake MFC Win32

If you ever tried RichEdit control in Vc++ , may be at first use you will notice that your application may crash , or the dialog is not coming.  The problem is , the RichEdit module is not loaded to memory initially. We need to load it explicitly. IF you are using MFC there are functions like
AfxInitRichEdit2(); // RichEdit Version 2
and
AfxInitRichEdit();  // RichEdit version 1.
If you are doing pure win32 , just by loading the richedit2.dll to meory will solve the problems , like
LoadLibrary("c:\\WINDOWS\\system32\\riched20.dll"); // this is richedit version 2.also remember to unload the module with FreeLibrary function.
You need to call the approrpiate function (AfxInitRichEdit or LoadLibrary) before creating richedit. The best way is to call is  in the InitInstance in MFC , or winmain Win32.

## Thursday, July 26, 2007

### Empty class size c++

People may thinks like the size is zero for an empty class (Me also thought
i
n the beginning). But it is not true. The size of an empty class will be never
zero. It is nonzero. There are two reasons for that.

1) the sizeof operator in c++ never returns zero.
2) IF the size becomes zero it may cause to have some invalid address
arithmetic operations.

so the size of an empty class is never zero , it is always nonzero (and this
value depends on compiler).

## Friday, July 6, 2007

### Placement New

This is not a new subject. Many of us knows this. Many not knows.
Placement new means we can ask the new operator to allocate from a particular memory area. This can be useful when implementing memory pools , to avoid fragmentation of memory.

This is the way to do this.

// Our mem pool of size 1000 bytes.
unsigend char *pMemPool = new unsigned char [1000]; // 1000 bytes is a sample ,use large numbers here.

Now i can ask new to allocate to pMemPool like this

Someclass *p = new (pMemPool) new Someclass;

When comparing the p and (Someclass *) pMemPool reveals they are equal. Don't free p, it will delete whole memory pool ( pMemPool). So allocate as much possible to this memory pool, later we can delete the whole pool . This helps to avoid memory fragmentation.

## Monday, June 11, 2007

### Unique instance creator using templates C++

I am presenting an idea to create a unique instance of an object using templates.. This is very similar to Singleton design pattern..
The code may be look like this

class UniqueFactory

{

private :

UniqueFactory()
{
}
public :

static T * Instance()
{
static T* ptr = new T();
return ptr;
}
};
So it will give the same instance of the object always.. For example
int *pInst = UniqueFactory<int>::Instance();
*pInst = 11;
pInst = UniqueFactory<int>::Instance();
*pInst , points to the same unique instance.
Another example is ( UserData can be any struct or class etc. )
UserData *pData = UniqueFactory<UserData>::Instance();
Hopes you may like it..!!

## Thursday, June 7, 2007

### Non-Polymorphic class And dynamic_cast

dynamic_cast, Non_polymorphic class , Some mfc thoughts
----------------------------------------------------------------------------------------

dynamic_cast couldn't be applied to "non-polymorphic" class . So what is this "non-polymorphic" class ? A class which has no virtual function is caled the non_polymorphic class. If you try to use dynamic_cast with non-polymorphic class. the result will be compile error. For example the code written below cause to an error.

class SuperBase
{
};
class Derived : public SuperBase
{
};

Derived* pDer = new Derived;
SuperBase* pBase = pDer;
Derived* pTest = dynamic_cast<Derived*>(pBase);

This code will try to cast pBase to Derived* , but it will not compile. To correct it use static_cast.

Derived* pTest = static_cast<Derived*>(pBase);

See the code below
CWnd *pWnd = GetDlgItem(IDC_BUTTON1); // IDC_BUTTON1 is a windows button control in a dialog.

Try to cast this pWnd to CButton* with dynamic_cast will give you a null pointer, like dynamic_cast<CButton*>(pWnd) will give you a null pointer. Means the cast is not working . Why ?????

Because mfc is creating some temporary objects inside , to reduce overehad. I will try to explain this later....

## Sunday, June 3, 2007

### Difference Between Parent And Owner windows

Parent , Owner Windows Vc++
--------------------------------------------

We all know the relation ship between parent and child windows.
So if i ask you this question "What is the difference between Owner window andv owned window' ?? If you know the answer leave now.. No need to read the rest of the page. Otherwise you may find it interesting to read.

I don't want to write more about this topic.. Since this is a simple question..
Child window means , its drawing is limited to the parent region , and also it z order is also changed according to parent.

But if you consider owner windows it can draw outside the parent window region ,
But if you close the main Top-level window , both of these windows will close..

So when creating a child window using CreateWindow function , there is an option for providing parent for the window.

If you are creating a child window with WS_POPUP style that window automatically becomes a owner window, and it can draw outside the region)(means (o,0) position indicates top Left corner of desktop). Otherwise it is a normal child window.
That's it...

## Monday, May 28, 2007

### MFC Temporary Handles

If we want a CWnd object from  a hwnd , the first functions coming to my mind is these.
CWnd -> Attach()
or
CWnd::FromHandle().

The difference is this , the CWnd::FromHandle first checks if the specified hwnd is already in the Permenent handle map. If so it
returns the CWnd * from the map. If it can't find it searches in the Temporary map and returns. if it couldn't see the hwnd in both
permenent and temporary map it will create a new CWnd * object and add it to temporary map.

So the point is this. The temporary objects are deleted during the idle time. So don't store the pointer returned from CWnd::FromHandle like functions ( CPen, CDC , CGDIObject etc ).

If we are calling Attach. it should be detached, otherwise during the destruction of the class (CWnd), the destructor calls the ::DestroyWindow API , to destroy the attached window( may be we don't want to do that). Also don't give non-MFC window pointer to Attach function. It is not valid . If you want , then use FromHandle function

## Monday, May 14, 2007

### A Easy message filter to a Win32 application vc++.

IF you know c# or vc.Net you can see interfaces like IMessageFilter , which allows to filter a particular message from the application.

So this can be done in win32 with some lines of coding , no need for any interface :)).
I don't want to explain anything more than these code snippets.We know every win32 app has a message loop. it may be look like this

while(GetMessage(&msg, NULL, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}

So we can add filter , which will filter all WM_LBUTTONDOWN message from this application by a mere checking, like
while (GetMessage(&msg, NULL, 0, 0))
{
if (msg.message != WM_LBUTTONDOWN && !TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}

Thats all..

## Friday, May 11, 2007

### Why ++i is faster than i++

Why ++i is faster than i++. Are you ever heard meaning less
discussions like "which is More Fast i++ or  ++ i"? or ++j or j++ or ++k or k++ . hahahaha.

IF you are serious I can say it will depends upon what is this i and j. If these variables are mere integers it
doesn't matter. We can use both. Both of them are of same speed. Then Problem is with floating point? Or double?.. No noo.. :). Actually there is no problem for ++i or i++.

The problem comes when people do
coding without concentration. Let us look the following example.

class COperator
{
int i;

public:
COperator(){i= 0;}
COperator&
operator ++()
{
i++;
return
*this;
}
COperator operator ++(int)
{
COperator temp = *this;
i++;
return temp;
}

};

In an expression as shown in below ,

COperator
it; // now i =0
it++; //
now i is 1
COperator
pt = it++; //now pt.i = 1 & it.i = 2;

Here for preserving the behaviour of original posix operator(I++), there is a
need for creating the temporary object in the stack((look operator ++(int) ) ,
and we return the temporary object.

So the point is this , some times in loops we often use i++ than ++i. It is a style.
Ok , but is good with integers(etc). But in case of class the obj++ will create
a extra object in stack and there is also a copy operation
. Since in loops
we need is a just an increment (or something like that). That’s why it is
prefered to use ++it rather than I++. If you ever programmed with STL you can
see that STL list uses iterators. They are class objects. So in that iterating
loops use ++it rather than it++. This will save some computing time and memory.

## Tuesday, May 8, 2007

### OpenMP with Vc++

Microsoft Windows provides support for OpenMP standard. If you don't know what is OpenMP read this from wikipedia.

" The OpenMP (Open Multi-Processing) is an application programming interface (API) that supports multi-platform shared memory multiprocessing programming in C/C++ and Fortran on many architectures, including Unix and Microsoft Windows platforms. It consists of a set of compiler directives, library routines, and environment variables that influence run-time behavior."

In VC++ this OpenMP can be called using #pragma omp <> directvies.
OpeMP is mainly used for parellel computing in the applications. Thread is created in openMp is like this
#pragma omp parallel num_threads(count ) , So the codes after this directive will be excuted in separte threads. count is the thread count.

For example
#pragma omp parallel num_threads(3)
{
}

Here we can see 3 different message box while the running this program. it is not possible to "return" or "goto" from inside the omp blocks.
Another example is parallely computing the sum of numbers in an array. Like this

int arry[10] = {1,2,3,4,5,6,7,8,9,10};
#pragma omp parallel for

for(int i = 0; i < 10;i++)
{
sum+=arry[i];
}

Note:  For using OpenMp in you application , you should provide the switch /openmp in compiler options.
1 . http://en.wikipedia.org/wiki/OpenMP
2.http://developers.sun.com/sunstudio/articles/omp-intro.html

## Monday, May 7, 2007

### Calculation using templates c++.

C++ Templates can also be used to evaluate an expression. Here i am just putting an example ( got from internet , and is working).
This template class can be used to find the factorial of a number. Actually the compiler calculates the factorial at compile time , during the template parsing.

template <int T>
class Factorial
{
public :
// Recursive definition
enum { GetValue = T * Factorial<T-1>::GetValue };
};

// specialization.
template <>
class Factorial<1>
{
public :
enum { GetValue = 1 };

};

we can find the factorial using the class Factorial. For example Factorial<5>::GetValue will give the factorial of 5. Factorial of 1 is handled as a special way (Just to exit) . So the code may look like this

int fact = Factorial<5>::GetValue;

If you try to find the factorial of 0 the visual studio will crash , Not the application :), because the factorial is computed by the compiler.Because if we put zero, there is no way to exit the compilation process (check with above codes). So you may need to handle 0 as a special case. or change the specialization to Factorial<0>

Note : Use of this feature will cause to slow down the compiling process.

### Easy way to Disable IME window in an Win32 Application

In this world of Unicode still we often do non Unicode applications. But there is a feature in windows operating system it allows to enter Unicode characters or characters other than basic ascii character set to our application.So What happens is when user press enter key these unicode characters will turn to "????" .Because our application is non Unicode .

So there is a easy way to disappear this IME window when our application comes to front. Microsoft provides api like

1 ImmDisableIme
2 ImmAssociateContext

So if you want to make disappear the ime window for a particular window in you application , you can use ImmAssociateContext.

like ImmAssociateContext(YourHwnd,0) , If don't wan to use the ime feature at all use ImmDisableIme().

The ImmDisableIme will cause to disable IME for all windows in you application .One important thing you should call this function , before any window is created.
Like ImmDisableIme( GetCurrentThreadID()). For an mfc application the best place to call is from CYourApp::InitInstance() , where CYourApp derived from CWinApp.

## Wednesday, May 2, 2007

### goto and static.

I don't want nothing much to write here except the following code sequence.Can anyone predict the outout???

int _tmain(int argc, _TCHAR* argv[])

{

goto XXX;

static int u = 90;

XXX:

printf("%d",u);

return 0;

}

It is 90 , that is the variable u getting the value 90. How the u gets this value ? .Eventough there is a goto before the assignent statement.

If you debug the following code you can see that the control never goes to the line "static test u = 90;" .Oho god how this happens???.

I think the compiler will handle the static variables while on the program loading. Because compiler need to reserve memory for a static variable whether it is declared in local function or global , it doesn't matter. Thats how here the variable u gets the value 90. if it is not a static variable the the program crashes without asking anybody.

If you try the same code replacing integer u with a some class object , like

class test
{

public :
int val;
test()
{
val = 90;
}

};

int _tmain(int argc, _TCHAR* argv[])
{

goto XXX;
static test u;
XXX:
printf("%d",u.val);

return 0;

}

you will never get the value 90 as output. Because the construcor is not called by the compiler eventhough it is static object.

So summarizing the facts , it will be like this.

1. static varibles memory allocation happens in anycase.
2. compiler also saves the value to the varible in statement like static int s = 90;
3 If you have class and it has a constructor accepting an integer , you can write like

static MyClass obj = 90; (But it will not get called ever, in our case)

Any comments , welcome!!!.

Note : I have tried the above test with VS2005 only. This behavior is compiler dependent.

## Tuesday, April 17, 2007

### Template Function in CPP file

Is it possible to do that ?? i mean writing template functions in c++ file ??? , Yeah it is possible.
Suppose we have class , its name is CSimple.

so the header may look like this
///CSimple.h
template <typename T>
class CSimple
{
T anything;
public :
void SimpleTest();
};
So we need to put the SimpleTest function outside the class. If it is the same header file , it is fairly easy to do
like this
template <typename T>
void CSimple<T> :: SimpleTest()
{
}
thats all. No pains. But it is in the c++ file you will get linker error (At least in VS ).
So to do that we can define .cpp file as this

// CSimple.cpp
#include
"CSimple.h"
template <typename T>
void CSimple<T> :: SimpleTest()
{

}
template CSimple<int>;
so in your main if are creating a creating an object of template class like CSimple<int> it will compile perfectly.

If u are creating objects of other types you have to give that class information in the cpp file. Like if you want to instantiate the template class with float you need to give template CSimple<float> in the cpp files. So sometimes it may not be possible to modify cpp files. So it is better to create a new cpp files and include the original cpp in that , also we can define our template class in that too. Like shown below

/// CComplex.cpp
#include "CSimple.cpp"
template  CSimple <float>

This will work definitely .

## Sunday, April 1, 2007

### STL vector and list Difference

If you are using STL fist time , you can see that these are the classes for holding a gropup of things.
You need to include #include <vector> and #include <list> for using these classes, also specify they are in std namespace . This can be done by using namespace std;

We all know these stuff. So what is the difference between vector and list ? When i compared the names first time , i can't see any difference, vector is something which has magnitude and direction in maths ( just joking) and list is our linked list ( doubly or single ).  No it is not like that , Actually the vector class only allows to insert in the back side or front side ( No addition in between ). But list allows.  list has function like insert() , using we can insert to any position. You may think then why we need vector? Ofcourse we need because , list costs perfomance degrade for allowing us to insertion in between the two ends. So IF you don't want to insert in between the front and last end , use vector. This can be speed up your performance.

One other difference is in vector each elements can be accesses using [] . But in list it won't possible.

These are the Key differece. In implementation wise vector is like dynamic array (When i say dynamic array u may think that "Is that same linked list ???"  , Not exactly ,the STL doc says that they have done some perfomance tuning for vector) , and list is the same linke list

## Tuesday, March 13, 2007

### Microsoft Visual Studio's intellisense BUG

I have found an interesting bug in VS 6 - VS 2003. (VC++ workspace )
Try typing the following lines ( You may not need to type all in some case ) , wait some time if nothing happens try compiling.

void operator :(int kd)
{

}

U will see that it is gone , i mean the VS. it is crashed by its own intelisense.... Suppose if you saved these lines to anyone of your friends projects he will never be able to open his project .. hahaha.. I am sure he will try restarting the OS , (may reinstalling the VS etcc ). Do that with your own riskk.....

## Monday, January 29, 2007

### Simple Particle Rendering.

Particles are really nice to see. usually we can see particle effects in most computer games . They appear as water fountain , flame, wind,sand, etc. It has infinite scope.  Actully we can create anything using particles.. But it will depends on the speed of computer.

In this page i am trying to create a simple particle engine , which renders a water fountain. So what is a particle ? the first answer coming to my mind is it is a point , but this is not fully correct. It can be represented as a point , or triangle , or polygon etc. This will depends on the application which we are writing. For the creation of water fountain we can assume the following attributes for a particle.

It is represented a single point . (GL_POINT in opengl )
it has 3 dimensions.
if follows gravity rules.  ( if we are using gravity).
it has a specific acceleration in all directions. ( 3 directions , x , y z).

Above are the basic things to keep in mind. So now we can create a structure like this

struct Particles
{

double xPos,yPos,zPos;
double xAcc; // xAcc is a constant one.
double yAcc; // this is a diminishing one due to the gravity.
double zAcc; // For the timebeing this is zero.
};
and
#define XACC .05
int        YACC 1.0

now we can create a bunch of particles by declaring an array of Particles.
Particles fountain[MAX_NUMS];

Now we need to design in which way one particle travels. it can be like this in a X-Y plane ( now no depth)

o  o
o         o
o             o
o               o

so for simulating the movement of a single particle we need to make changes on both x , y .we can keep the x acceleration as constant number ( Particles::xAcc) . If u look the image more closely it can be seen that the acceleration in y direction is more compared to X ,  it is also decreasing due to gravity.

so we can do it like this, For each particle particle[i].x += XACC ( constant) , and particle[i].y += particle[i].yAcc; so initially this particle[i].yAcc is initialized to 1. after each rendering this will be decreased by the amount of gravity , like  particle[i].yAcc-=gravity; so when the yAcc becomes -ve we will get a falling effect.

If a particles y value is  -ve and x value is +ve it means that , that particles is falled down to ground. so we need to again reinitialize it position to zero , again sets its acceleration and gravity to the predefined value...

Till now we have drawn only particles in 2d space, ie we haven't changed the z value. we can do that by giving rotating about y axis. The pseudo code is shown below..

For(int i = 0; i < TOT_PARTICLE;i++)
{

for(int j = 10; j < 360 ; j+=90)
{

glRoate(j degrees in y axis);
Apply colors or textures.
DrawParticle(particle[i].x,particle[i].y,particle[i].z);
ChangeAccleration(particle[i]); // here we are changing the accleration in both y and x direction
}
};

Now it is complete I am attaching a sample screen shot which i did with this idea. Hopes this may give some good starting for beginners who want to learn particles.