Tuesday, 25 August 2009
A Macro Pitfall Question
#define max1(a,b) a < b ? b : a
#define max2(a,b) (a) < (b) ? (b) : (a)
what would be the value of x in the following cases:
x = max1(i += 3, j);
x = max2(i += 3, j);
and why?
Assume that initial value of i = 5 and j = 7 in both the cases. What is the value of i and j after the Macro?
Answer:
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
In case of max1, x = 12, i = 12 and j = 7. The reason being the substitution will happen like this:
i += 3 < j ? j : i += 3
which using operator precedence rules and language rules means:
i += ((3 < j) ? j : i += 3). Since 3 < 7, i = i + j = 12 which is the same as x.
In case of max2, x = 11, i = 11 and j = 7. The reason being the substitution will happen like this:
(i += 3) < (j) ? (j) : (i += 3). Since 5+3 = 8 which is > 7, i+=3 will be executed again (2nd time) so 5+6 = 11 which is the value of i and x.
Saturday, 22 August 2009
Measuring elapsed time in C++ using timeGetTime()
So whats the difference and which one is better. timeGetTime() has a default resolution of around 5ms but by using the timeBeginPeriod(1) the accuracy can be made upto 1ms. GetTickCount accuracy and jitter cannot be guaranteed. timeGetTime() has more overhead than GetTickCount() so it should not be used in the case where the calls will be frequently made.
Another thing which may be obvious is that GetTickCount() actually calculates the time based on the number of clock interrupts and multiplies it by clock frequency. timeGetTime() reads a field called interrupt time which is updated by Kernel periodically.
Finally, if possible always use QueryPerformanceCounter() as thats better and receommended.
//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//This program shows example of Getting Elapsed Time
#include <iostream>
#include <Windows.h>
using namespace std;
unsigned long startTime_;
void startTime()
{
startTime_ = timeGetTime();
}
unsigned int calculateElapsedTime()
{
unsigned int diffInMilliSeconds = timeGetTime() - startTime_;
return diffInMilliSeconds;
}
int main()
{
//Increasing the accuracy of Sleep to 1ms using timeBeginPeriod
timeBeginPeriod(1); //Add Winmm.lib in Project
unsigned int diffTime = 0, lastTime = 0, newTime = 0;
startTime();
cout<<"Start Time = "<<calculateElapsedTime()<<endl;
Sleep(100);
newTime = calculateElapsedTime();
diffTime = newTime - lastTime;
cout<<"Time after 100ms Sleep = "<<newTime<<", Difference = "<<diffTime<<endl;
lastTime = newTime;
Sleep(100);
newTime = calculateElapsedTime();
diffTime = newTime - lastTime;
cout<<"Time after 100ms Sleep = "<<newTime<<", Difference = "<<diffTime<<endl;
lastTime = newTime;
Sleep(5);
newTime = calculateElapsedTime();
diffTime = newTime - lastTime;
cout<<"Time after 5ms Sleep = "<<newTime<<", Difference = "<<diffTime<<endl;
lastTime = newTime;
Sleep(50);
newTime = calculateElapsedTime();
diffTime = newTime - lastTime;
cout<<"Time after 50ms Sleep = "<<newTime<<", Difference = "<<diffTime<<endl;
timeEndPeriod(1); //Must be called if timeBeginPeriod() was called
return 0;
}
The output is as follows. Notice more reliable and jitter free output:
Friday, 21 August 2009
Measuring elapsed time in C++ using QueryPerformanceCounter()
Unlike the GetTickCount approach, which is not very reliable and does not have good resolution, this approach is quite reliable and has very good resolution, often better than a ms. The only problem with this approach used to be that in old systems it may not be very reliable. For example in some old OS (before XP sp2) in case of multiple processors present, and if the clocks of both the processors are not very well synchronised (doe to buggy hardware) then you can get different results each time the QueryPerformanceCounter call is made. Another problem with some chipsets with regards to their power saving is that the frequency changes while we use GetPerformanceFrequency call only once during the program. This can result in incorrect timing being returned. There were some other problems being present as well but they have now all seem to be fixed either in firmware or in the OS. It is recommended that this calls should only be used in OS greater than or equal to Windows XP SP2.
//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//This program shows example of Getting Elapsed Time
#include <iostream>
#include <Windows.h>
using namespace std;
LARGE_INTEGER timerFreq_;
LARGE_INTEGER counterAtStart_;
void startTime()
{
QueryPerformanceFrequency(&timerFreq_);
QueryPerformanceCounter(&counterAtStart_);
cout<<"timerFreq_ = "<<timerFreq_.QuadPart<<endl;
cout<<"counterAtStart_ = "<<counterAtStart_.QuadPart<<endl;
TIMECAPS ptc;
UINT cbtc = 8;
MMRESULT result = timeGetDevCaps(&ptc, cbtc);
if (result == TIMERR_NOERROR)
{
cout<<"Minimum resolution = "<<ptc.wPeriodMin<<endl;
cout<<"Maximum resolution = "<<ptc.wPeriodMax<<endl;
}
else
{
cout<<"result = TIMER ERROR"<<endl;
}
}
unsigned int calculateElapsedTime()
{
if (timerFreq_.QuadPart == 0)
{
return -1;
}
else
{
LARGE_INTEGER c;
QueryPerformanceCounter(&c);
return static_cast<unsigned int>( (c.QuadPart - counterAtStart_.QuadPart) * 1000 / timerFreq_.QuadPart );
}
}
int main()
{
//Increasing the accuracy of Sleep to 1ms using timeBeginPeriod
timeBeginPeriod(1); //Add Winmm.lib in Project
unsigned int diffTime = 0, lastTime = 0, newTime = 0;
startTime();
lastTime = calculateElapsedTime();
cout<<"Start Time = "<<lastTime<<endl;
Sleep(100);
newTime = calculateElapsedTime();
diffTime = newTime - lastTime;
cout<<"Time after 100ms Sleep = "<<newTime<<", Difference = "<<diffTime<<endl;
lastTime = newTime;
Sleep(100);
newTime = calculateElapsedTime();
diffTime = newTime - lastTime;
cout<<"Time after 100ms Sleep = "<<newTime<<", Difference = "<<diffTime<<endl;
lastTime = newTime;
Sleep(5);
newTime = calculateElapsedTime();
diffTime = newTime - lastTime;
cout<<"Time after 5ms Sleep = "<<newTime<<", Difference = "<<diffTime<<endl;
lastTime = newTime;
Sleep(50);
newTime = calculateElapsedTime();
diffTime = newTime - lastTime;
cout<<"Time after 50ms Sleep = "<<newTime<<", Difference = "<<diffTime<<endl;
timeEndPeriod(1); //Must be called if timeBeginPeriod() was called
return 0;
}
The output is as follows:
Thursday, 20 August 2009
Measuring elapsed time in C++ using GetTickCount()
//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//This program shows example of Getting Elapsed Time
#include <iostream>
#include <Windows.h>
using namespace std;
unsigned long startTime_;
void startTime()
{
startTime_ = GetTickCount();
}
unsigned int calculateElapsedTime()
{
unsigned int diffInMilliSeconds = GetTickCount() - startTime_;
return diffInMilliSeconds;
}
int main()
{
//Increasing the accuracy of Sleep to 1ms using timeBeginPeriod
timeBeginPeriod(1); //Add Winmm.lib in Project
unsigned int diffTime = 0, lastTime = 0, newTime = 0;
startTime();
cout<<"Start Time = "<<calculateElapsedTime()<<endl;
Sleep(100);
newTime = calculateElapsedTime();
diffTime = newTime - lastTime;
cout<<"Time after 100ms Sleep = "<<newTime<<", Difference = "<<diffTime<<endl;
lastTime = newTime;
Sleep(100);
newTime = calculateElapsedTime();
diffTime = newTime - lastTime;
cout<<"Time after 100ms Sleep = "<<newTime<<", Difference = "<<diffTime<<endl;
lastTime = newTime;
Sleep(5);
newTime = calculateElapsedTime();
diffTime = newTime - lastTime;
cout<<"Time after 5ms Sleep = "<<newTime<<", Difference = "<<diffTime<<endl;
lastTime = newTime;
Sleep(50);
newTime = calculateElapsedTime();
diffTime = newTime - lastTime;
cout<<"Time after 50ms Sleep = "<<newTime<<", Difference = "<<diffTime<<endl;
timeEndPeriod(1); //Must be called if timeBeginPeriod() was called
return 0;
}
The output is as follows:
Friday, 14 August 2009
Instantiating a Multimap inside a class
//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//This program shows use of multi-maps in a class
#include<iostream>
#include<map>
#include <string>
using namespace std;
class mapInstantiator
{
public:
~mapInstantiator();
void createMultiMap(void);
void insertElements(pair<string, int> element);
void printer(void);
private:
multimap<string, int> *phoneNums;
};
void mapInstantiator::createMultiMap(void)
{
//Instantiate
phoneNums = new multimap<string, int>;
}
void mapInstantiator::insertElements(pair<string, int> element)
{
phoneNums->insert(element);
}
void mapInstantiator::printer(void)
{
cout<<"\n\nMultimap printer method"<<endl;
cout<<"Map size = "<<phoneNums->size()<<endl;
multimap<string, int>::iterator it = phoneNums->begin();
while(it != phoneNums->end())
{
cout<<"Key = "<<it->first<<" Value = "<<it->second<<endl;
it++;
}
}
mapInstantiator::~mapInstantiator()
{
//Dont forget to delete the pointer
delete phoneNums;
}
int main()
{
mapInstantiator aClass;
aClass.createMultiMap();
//Insert key, value as pairs
aClass.insertElements(pair<string, int>("Joe",123));
aClass.insertElements(pair<string, int>("Will",444));
aClass.insertElements(pair<string, int>("Joe",369));
aClass.insertElements(pair<string, int>("Joe",812));
aClass.insertElements(pair<string, int>("Will",4556));
aClass.insertElements(pair<string, int>("Smith",71));
aClass.printer();
return 0;
}
The Output is as follows:
Tuesday, 11 August 2009
Functions returning void
"Can you write a return statement in a function that returns void?" The answer is "Yes! You can return void!"
The following is a simple program picked up from the same blog and modified showing a function returning void
//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//This is a simple example of a function returning void
#include<iostream>
using namespace std;
static void foo (void)
{
cout<<"foo() called"<<endl;
}
static void bar (void)
{
cout<<"bar() called"<<endl;
return foo(); // Note this return statement.
}
int main ()
{
cout<<"main() called"<<endl;
bar();
return 0;
}
The output is as follows:
This feature is very useful in case of Templates. Lets write a simple program that uses Templates:
//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//This is a simple example of a Template returning void
#include<iostream>
//#include <typeinfo> - Some compilers may need this
using namespace std;
template <class T> T FOO (void)
{
cout<<"T FOO() called with T = "<<typeid(T).name()<<endl;
return T(); // Default construction
}
template <class T> T BAR (void)
{
cout<<"T BAR() called with T = "<<typeid(T).name()<<endl;
return FOO<T>(); // Syntactic consistency. Same for int, void and everything else.
}
int main (void)
{
cout<<"main() called"<<endl;
BAR<void>();
BAR<int>();
BAR<char>();
}
The output is as follows:
Friday, 7 August 2009
Suppress Compiler Warning using #pragma
//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//This example shows how to suppress warnings using #pragma
#include<iostream>
using namespace std;
class error
{
public:
error(string s)
{
info = s;
}
private:
error();
string info;
};
#pragma warning( disable : 4290 )
int someFunc(void) throw (error)
{
return 1;
}
#pragma warning( default : 4290 )
int someOtherFunc(void) throw (error)
{
return 1;
}
int main()
{
return 0;
}
Here, for 'someOtherFunc', the compiler will generate a warning:
warning C4290: C++ exception specification ignored except to indicate a function is not __declspec(nothrow)
but a similar warning for 'someFunc' wont be generated because we have already suppressed it using the #pragma.
Wednesday, 5 August 2009
Const Pointer and References Table
Interesting table courtesy of my colleague Simon Locke about different possibilities of using const along with pointers and references.
Definition | Read-only | Ownership passed | Allows NULL |
| Type& | No | No | No |
| const Type& | Yes | No | No |
| Type* | No | Yes | Yes |
| const Type* | Yes | Yes | Yes |
| Type* const | No | No | Yes |
| const Type* const | Yes | No | Yes |
The definition field is the parameter being passed to a function or a return from the function. For example you can see an example here of the first definition of 'Type&'.
Sunday, 2 August 2009
Const after a function name
//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//This example shows what happens if const is put after a function
#include<iostream>
using namespace std;
class ABC
{
public:
int func1(int a, int b);
int func2(int a, int b) const;
private:
int x,y;
};
int ABC::func1(int a, int b)
{
x = a, y = b;
cout<<"x = "<<x<<" and y = "<<y<<endl;
return 0;
}
int ABC::func2(int a, int b) const
{
//x = a, y = b; - NOT POSSIBLE, Compile Error
cout<<"Cant change x and y"<<endl;
return -1;
}
int main()
{
ABC abc;
abc.func1(3, 7);
abc.func2(20, 40);
return 0;
}
The output is as follows:
Thursday, 30 July 2009
Virtual Base class Inheritance

Function main declares objects of classes Multiple, DerivedOne and DerivedTwo. main also declares an array of Base * pointers. Each array element is initialized with the address of an object. An error occurs when the address of both—an object of class Multiple—is assigned to array[ 0 ]. The object both actually contains two subobjects of type Base, so the compiler does not know which subobject the pointer array[ 0 ] should point to, and it generates a compilation error indicating an ambiguous conversion.
The problem of duplicate subobjects is resolved with virtual inheritance. When a base class is inherited as virtual, only one subobject will appear in the derived class—a process called virtual base-class inheritance.
//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Example showing virtual base class inheritance
//http://www.deitel.com/articles/cplusplus_tutorials/20060225/virtualBaseClass/index.html
#include <iostream>
using std::cout;
using std::endl;
// class Base definition
class Base
{
public:
virtual void print() const = 0; // pure virtual
}; // end class Base
// class DerivedOne definition
//class DerivedOne : public Base - REF1
class DerivedOne : virtual public Base
{
public:
// override print function
void print() const
{
cout << "DerivedOne\n";
} // end function print
}; // end class DerivedOne
// class DerivedTwo definition
//class DerivedTwo : public Base - REF2
class DerivedTwo : virtual public Base
{
public:
// override print function
void print() const
{
cout << "DerivedTwo\n";
} // end function print
}; // end class DerivedTwo
// class Multiple definition
class Multiple : public DerivedOne, DerivedTwo
{
public:
// qualify which version of function print
void print() const
{
DerivedTwo::print();
} // end function print
}; // end class Multiple
int main()
{
Multiple both; // instantiate Multiple object
DerivedOne one; // instantiate DerivedOne object
DerivedTwo two; // instantiate DerivedTwo object
Base *array[ 3 ]; // create array of base-class pointers
array[ 0 ] = &both; // ERROR - ambiguous if REF1 and REF2 used
array[ 1 ] = &one;
array[ 2 ] = &two;
// polymorphically invoke print
for ( int i = 0; i < 3; i++ )
array[ i ] -> print();
return 0;
} // end main


