C++
How to calculate log2 of any number?
1![]()
Few days back, my client give me one 4 inch long and 2 inch wide math equation to implement. Well, the equation contains log2 and while coding, my Visual Assist was not auto filling the log2 function. It just underlines the function by redline. When i checked the MSDN, I was shocked that log2 is not available as the part of standard library. So how to get the log2 of a number?

![]()
Log2 is pretty simple, nah? Its implementation as follows,
#include <math.h>
...
// Calculates log2 of number.
double Log2( double n )
{
// log(n)/log(2) is log2.
return log( n ) / log( 2 );
}
![]()
Its silly function, But I still blame standard library for not including it. Because I’m lazy.
![]()
Targeted Audience – Beginners.
How to sort an array by using STL?
2![]()
Today I’ll tell a story… Its interesting!
Once upon a time, there lived a C++ Padawan. One day, he want to sort an array. He knows that STL have std::sort() function. But he want to sort an array, not an STL container. What a fool he is? Native array’s don’t have iterators. So how could he call the std::sort() function? Well, he is clever – he created a vector, copied his array to vector, then he called the sort() function. After sorting, he copied the data back to array.
The End!

But now he is ashamed of what he did. Because now he realize that he can use std::sort() directly on native array too! But how?
![]()
You can use array pointers direclty in STL algorithms. They act like iterators itself. Have a look at the code snippet.
// Integer array with 10 items.
int Array[10] = { 9,3,2,4,0,6,7,8,1,5 };
// Sort them.
std::sort( Array, Array + 10 );
![]()
Well, Can you guess – who was that C++ trainee? It was me.
![]()
Targeted Audience – Beginners.
Accessing empty vector will always throw exception?
1![]()
Vectors are cool! if we access out of array, they will throw unhandled exception. I used to get a lot.

But are you sure that you’re vector always throw exception if you access out of array?
![]()
Answer is NO. Well have a look at the code snippet. At first we access an empty vector which throws an exception. Then we insert some values and then clear the vector to make it empty. Then if we access the empty vector, it won’t throw exception! Have a look at it.
// This class is just to access the protected members
// of vector.
class IntVector : vector<int>
{
friend void CheckVector();
};
void CheckVector()
{
IntVector IntArray;
try
{
// Try to access element which result in exception.
int Value = IntArray[ 0 ];
}
catch( ... )
{
// It will reach here since we're trying
// to access an empty vector.
}
// Now add one value and clear the vector.
IntArray.push_back( 10 );
IntArray.clear();
try
{
// Now try to access element. You can access it
// eventhough the vector is empty.
int Value = IntArray[ 0 ];
}
catch( ... )
{
// It will not reach here.
}
// Check the size of memory allocation inside vector.
int InternalSize = _msize( IntArray._First );
int VectorSize = IntArray.size();
Well, the reason is optimization. While clearing the vector, for optimization it won’t removes the allocated memory. It just sets the size as 0. So if you access the data by using array operator, you’ll get old value.
![]()
The morel is always check the size of array before accessing it. Well the behavior is observed in Visual Studio 6.0. Different IDEs and platforms may show different behavior. Take care!
![]()
Targeted Audience – Intermediate.
What is Name Mangling and how to disable Name Mangling?
1![]()
What is Name Mangling?
Name mangling is the technique used by C++ to generate unique names. C++ uses name mangling to implement function overloading etc. For instance, if you have two overloaded functions, while compiling the source, compiler will internally rename your function to uniquely generated function name. The function name is generated from the parameter list and a couple of other factors.
Check the links for the name mangling algorithm by Visual C++.
http://en.wikipedia.org/wiki/Microsoft_Visual_C%2B%2B_Name_Mangling
http://www.kegel.com/mangle.html
Have a look at mangled C++ function names below.

Well, Name Mangling is nice. But it have one problem. You cannot call your exported C++ function from C code. Because, C++ compiler mangles the function name and renames the fuction and exposes the mangled function name. So in order for C source to call C++ function, you’ve to disable name mangling for those functions. But how?
![]()
You can disable name mangling by declaring the function as extern “C”. Have a look at the code snippet.
// Disable name Mangling for single function.
extern "C" void Function( int a, int b );
// Disable name Mangling for group of functions.
extern "C"
{
void Function1( char a, char b );
void Function2( int a, int b );
void Function3( float a, float b );
}
![]()
If you want to get the function name from a mangled name, then have a look at my previous post -
http://weseetips.com/2008/04/14/name-mangling-how-to-undecorate-a-c-decorated-function-name/
![]()
Targeted Audience – Beginners.
dynamic_cast throws unhandled exception during Reverse Polymorphism?
1![]()
What is Reverse Polymorphism?
Casting Base class object to derived class pointer is called Reverse Polymorphism or Inverse Polymorphism. Check the following code block.
// Base class.
class Base
{
public:
virtual ~Base() {}
};
// Derived class.
class Derived : public Base
{
public:
virtual ~Derived() {}
};
void CDialogDlg::OnButton4()
{
// Base instance.
Base* pBase = new Base;
// Reverse Polymorphism. Cast Base Object to derived.
Derived* pDerived = dynamic_cast<Derived*>( pBase );
}
While casting by using dynamic_cast, possible you may hit un-handled exception as follows.

Ideally dynamic_cast should return null, since its an invalid casting. But why its throwing un-handled exception? Is there something to do?
![]()
You’ve to enable RTTI. If RTTI is not enabled, it will throw un-handled exception for reverse polymorphism. For enabling RTTI,
1) Take project settings,
2) Take C/C++ tab.
3) In “C++ Language” category, enable RTTI. See the screenshot.

![]()
This is not a standard C++ behavior. This one is checked only in Visual C++ 6.0 compiler. You may or may not encounter the behavior in other Microsoft compiler version or in other compilers. So take care!
![]()
Targeted Audience – Intermediate.
Function call by using null pointer will crash?
3![]()
Crash on function call by using null pointer – The ultimate C++ Nirvana.
Whether function call by null pointer always crash? Is it possible to call functions by using null pointer without crash? Check the following code snippet. Whether it will crash?
// Console Helper class.
class ConsoleHelper
{
public:
// Prints a line to console.
void PrintLine()
{
cout << "---------------" << endl;
}
};
// The one and only one Main.
int main(int argc, char* argv[])
{
// Call the function by using null pointer.
ConsoleHelper* pConsoleHelper = 0;
pConsoleHelper->PrintLine();
return 0;
}
![]()
It won’t crash. Because in the function call we’re not accessing any member variables. Function call by using null pointers crash only if we’re accessing some member variables. Its because for every object function call, the object address is pushed to the function stack as “this” pointer. If the object pointer is null, then the “this” pointer also become null and hence the crash!
![]()
Null pointers are not that much bad! isn’t it?
![]()
Targeted Audience – Intermediate.
How to manipulate bits easily?
0![]()
We usually use & operator for checking bits in an integer value. Is there any easy method to manipulate bits? You can use STL bitset container. But it’s not a container like vector or list. So it does not have iterators.
![]()
The bitset should be initialized with the number of bits. See the sample code block below.
// Initialize bitset with number of bits required. // Here its for holding an integer. bitset<sizeof(int) * 8> IntegerBits = 12478; // I wanna see the value in binary. cout << "Binary of 12478 is :" << IntegerBits << endl; // How many bits are present? cout << "Number of bits:" << IntegerBits.size() << endl; // Check whether 10th bit is set. cout << "10th bit is:" << IntegerBits[10] << endl; // Flip all bits and display. IntegerBits.flip(); cout << "Flipped Binary of 12478 is :" << IntegerBits << endl;
Now getting and manipulating bits is just like a breeze. nah?
![]()
Targeted Audience – Beginners.
How to catch exceptions from constructor initializer list?
4![]()
C++ provides constructor initializer list to initialize member variables of type reference, const etc. In the constructor initialize list, we can initialize ordinary objects too. See sample below.
MyClass::MyClass( int var1, int var2 )
: m_var1( var1 ),
m_obj2( var1 ) // If this one throws an exception,
// it can't be caught.
{
try
{
// Constructor body.
}
catch( ... )
{ }
}
But did you noticed that, these constructor initialize list is outside the function body, and if an exception is thrown from any of the member variable’s constructor, how it can be caught?
![]()
There is a special kind of try-catch usage to catch exceptions from constructor initialize list. See the code snippet below.
MyClass::MyClass( int var1, int var2 )
try : m_var1( var1 ),
m_obj2( var1 ) // Now I can catch the exception.
{
// Constructor body.
}
catch( ... )
{ }
Now you can catch exceptions from constructor member initializer list also.
![]()
You cannot compile this in Visual C++ 6.0, since its does not strictly confirms C++ standards. You can compile this on Visual Studio 7.0 onwards.
![]()
Targeted Audience – Intermediate.
Use printf() while tracing from multithreaded console applications.
2![]()
Usually most of our back end server applications might be multi-threaded console applications which contain several threads running simultaneously. Usually we do trace issues by printing strings to console screen by using cout or printf(). As a general practice, we usually stick upon cout because of our affinity towards C++.
But there is a great pitfall lies behind.
![]()
If you use cout, you can see the traces are shuffled and displayed only after certain interval. This is because, cout uses buffered output. So if you need real time tracing, use printf().
if you still want to use cout, then flush the streams by calling flush(). See the code snippt.
// Trace the message. cout << _T( "Tracing from thread" ); // flush the buffer. cout.flush();
![]()
This difference may not be visible if you are running one thread at a time. If you have a number of threads and each one is busy in dumping traces, definitely you can see this.
![]()
Targeted Audience – Intermediate.
How to include special characters in string?
3![]()
In C++ programs, sometimes you’ve to add special chars to your strings. For instance a copyright message – “Copyright © WeSeeTips.com”. If your editor like Visual Studio support unicode, you can directly paste it to the source. But not all editors are unicode aware. So what’s the safest method?
![]()
You can use C++ escape sequence – \x. The \x followed by hexadecimal value of char will insert that char to the string. For instance the hex of © is oxA9. See how it can be added to a string.
// 0xA9 is the hex for copyright symbol.
const TCHAR* pCopyright = _T("Copyright \xA9 WeSeeTips.com");
AfxMessageBox( pCopyright );
![]()
Its worth reading about trigraphs chars at this moment.
http://weseetips.com/2008/03/25/trigraph-char-sequences-in-c-c/
![]()
Targeted Audience – Beginners.