Wednesday, 17 February 2010

What is the output of this tricky program?

Interesting problem from C Programming tricks:



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>

using namespace
std;

int
main()
{

int
a=2,*f1,*f2;
f1=f2=&a;
*
f2+=*f2+=a+=2.5;
*
f1+=*f1+=a+=2.5;
cout<<"a = "<<a<<" *f1 = "<<*f1<<" *f2 = "<<*f2<<endl;

return
0;
}






What is the final value of a, *f1 and *f2. Choose one from below:
a) 18,18,18
b) 10,10,10
c) 72,72,72
d) 64,64,64
e) 26,26,26

The answer is...
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.


Wednesday, 10 February 2010

Synchronous and Asynchronous calls in C++

Sometimes there can be confusion between Synchronous and Asynchronous calls. A synchronous call is the one in which the function/call/procedure has to return before the next statement can be executed. What this means is that the function is blocking the rest of the code.

In asynchronous calling, generally there would be multiple threads. So a function call on one thread will probably not block the function call on other thread. That means that both the functions are asynchronous.

Here is a simple example that I have modified from an earlier example to show synchronous and asynchronous calling:



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Example from http://www.adrianxw.dk/SoftwareSite/Threads/Threads2.html
//This shows an example of Synchronous and Asynchronous function calls
#include <windows.h>
#include <process.h>
#include <iostream>
using namespace std;

void
Func1(void *);
void
Func2(void *);

CRITICAL_SECTION Section; //This will act as Mutex


int
main()
{

InitializeCriticalSection(&Section);

//Synchronous calling
cout<<"\nSynchronous calling"<<endl;
Func1(0);
Func2(0);

//Asynchronous calling
cout<<"\nAsynchronous calling"<<endl;
HANDLE hThreads[2];

//Create two threads and start them
hThreads[0] = (HANDLE)_beginthread(Func1, 0, NULL);
hThreads[1] = (HANDLE)_beginthread(Func2, 0, NULL);

//Makes sure that both the threads have finished before going further
WaitForMultipleObjects(2, hThreads, TRUE, INFINITE);

//This is done after all threads have finished processing
DeleteCriticalSection(&Section);

cout << "Main exit" << endl;
return
0;
}


void
Func1(void *P)
{

int
Count;

for
(Count = 1; Count < 11; Count++)
{

EnterCriticalSection(&Section);
cout << "Func1 loop " << Count << endl;
LeaveCriticalSection(&Section);
Sleep(1000);
}

return
;
}


void
Func2(void *P)
{

int
Count;

for
(Count = 10; Count > 0; Count--)
{

EnterCriticalSection(&Section);
cout << "Func2 loop " << Count << endl;
LeaveCriticalSection(&Section);
Sleep(1000);
}

return
;
}







The output is as follows:

Wednesday, 3 February 2010

reinterpret_cast in C++

From the Cpp Reference:

Syntax: TYPE reinterpret_cast (object);

The reinterpret_cast operator changes one data type into another. It should be used to cast between incompatible pointer types.

Suppose we have two variables, int a and char b

In C programming we can covert from b to a by:
a = (int)b;

In C++, the proper way to do this would be by using cast. One way is to use:
a = reinterpret_cast(b);

Most of the time reinterpret_cast is not required in the programs and can often be very dangerous. The following is from MSDN:

The reinterpret_cast operator also allows any integral type to be converted into any pointer type and vice versa. Misuse of the reinterpret_cast operator can easily be unsafe. Unless the desired conversion is inherently low-level, you should use one of the other cast operators.

The reinterpret_cast operator can be used for conversions such as char* to int*, or One_class* to Unrelated_class*, which are inherently unsafe.

The result of a reinterpret_cast cannot safely be used for anything other than being cast back to its original type. Other uses are, at best, nonportable.

The reinterpret_cast operator cannot cast away the const, volatile, or __unaligned attributes. See const_cast Operator for information on removing these attributes.

The reinterpret_cast operator converts a null pointer value to the null pointer value of the destination type.

One practical use of reinterpret_cast is in a hash function, which maps a value to an index in such a way that two distinct values rarely end up with the same index.

Instead of reinterpret_cast people generally prefer static_cast

Lets look at an example of reinterpret_cast:





//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>

using namespace
std;

int
main()
{

int
a = 22;
float
b = (float)33.3333;

cout<<"1. a = "<< a <<" b = "<< b <<endl;

a = (int)b; //Old C programming way
cout<<"2. a = "<< a <<" b = "<< b <<endl;

//Wont work in this case because floating point format is different
a = reinterpret_cast<int&>(b);
cout<<"3. a = "<< a <<" b = "<< b <<endl;

a = static_cast<int>(b); //Correct approach
cout<<"4. a = "<< a <<" b = "<< b <<endl;

char
c;
//Convert int to char
c = reinterpret_cast<char&>(a);
cout<<"5. c = "<< (int)c <<" a = "<< a <<endl;

//Dangerous to convert from char to int
a = reinterpret_cast<int&>(c);
cout<<"6. c = "<< (int)c <<" a = "<< a <<endl;

//What we actually wanted was just the last 8 bits so...
a = a & 0x000000FF; //00 = 8 bits
cout<<"7. c = "<< (int)c <<" a = "<< a <<endl;

return
0;
}






The output is as follows:

Wednesday, 27 January 2010

Memory Allocation example for Double Pointer of a class

The following program should be self explanatory:



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Program to demonstrate memory allocation to double pointers
#include<iostream>

using namespace
std;

//Class named NewClass
class NewClass
{

public
:
int
a;
int
* b;
void
* c;
};


//List Structure containing multiple NewClass objects
struct NewClassList
{

int
numOfObjects;
NewClass** Objects;
};


int
main()
{

//Create NewClassList with 4 objects with following values:
//1, 10, 100; 2, 20; 200; 3, 30, 300; 4, 40, 400;
NewClassList someList;
someList.numOfObjects = 4;
//someList.Objects = new NewClass*; //1. Common mistake in allocating memory
someList.Objects = new NewClass*[someList.numOfObjects];

someList.Objects[0] = new NewClass;
someList.Objects[0]->a = 1;
someList.Objects[0]->b = new int(10);
someList.Objects[0]->c = (void*) new int(100);

someList.Objects[1] = new NewClass;
someList.Objects[1]->a = 2;
someList.Objects[1]->b = new int(20);
someList.Objects[1]->c = (void*) new int(200);

someList.Objects[2] = new NewClass;
someList.Objects[2]->a = 3;
someList.Objects[2]->b = new int(30);
someList.Objects[2]->c = (void*) new int(300);

someList.Objects[3] = new NewClass;
someList.Objects[3]->a = 4;
someList.Objects[3]->b = new int(40);
someList.Objects[3]->c = (void*) new int(400);

//Printing the outputs
for(int i = 0; i < someList.numOfObjects; i++)
{

cout<<"Iteration = "<<i;
cout<<": a = "<<someList.Objects[i]->a;
cout<<": b = "<<*(someList.Objects[i]->b);
cout<<": c = "<<*((int*)someList.Objects[i]->c)<<endl;
}


//Clear all the memory allocation
for(int i = 0; i < someList.numOfObjects; i++)
{

delete
someList.Objects[i]->b;
delete
someList.Objects[i]->c;
delete
someList.Objects[i];
}

delete
[] someList.Objects;
return
0;
}





The output is as follows:

Tuesday, 19 January 2010

The Unmanaged Pointer problem

This is an interesting problem from More Exceptional C++: 40 New Engineering Puzzles, Programming Problems, and Solutions by Herb Sutter. See Amazon link at the bottom of the post.

In your travels through the dusty corners of your company's code archives, you find the following code fragment:

// Example 20-2
//

// In some header file:
void f( T1*, T2* );

// In some implementation file:
f( new T1, new T2 );

Does this code have any potential exception safety problems?

On a personal note, I have seen people trying to do as much as possible on a single line thinking that they are writing optimised code. This may be true in some very rare instances but in most of the cases this is not true. Performing multiple operations in a single statement can cause side effects like memory leaks or incorrect operation, it can also make the code less readable and can cause difficulty in debugging.

Going back to the problem at hand, according to Herb Sutter there are several potential exception safety problems with the above code. An expression such as new T1 is called, simply enough, a new-expression. Recall what a new-expression really does:

* It allocates memory;
* It constructs a new object in that memory; and
* If the construction fails because of an exception the allocated memory is freed.

So each new-expression is essentially a series of two function calls: one call to operator new() (either the global one, or one provided by the type of the object being created), and then a call to the constructor.

So in case of a function defined as f( expr1, expr2 );

consider what happens if the compiler decides to generate code as follows:

1. allocate memory for the T1
2. construct the T1
3. allocate memory for the T2
4. construct the T2
5. call f()

The problem is this: If either step 3 or step 4 fails because of an exception, the C++ standard does not require that the T1 object be destroyed and its memory deallocated. This is a classic memory leak, and clearly Not a Good Thing.

Another possible sequence of events is the following:

1. allocate memory for the T1
2. allocate memory for the T2
3. construct the T1
4. construct the T2
5. call f()

This sequence has not one, but two exception safety problems with different effects:

If step 3 fails because of an exception, then the memory allocated for the T1 object is automatically deallocated (step 1 is undone), but the standard does not require that the memory allocated for the T2 object be deallocated. The memory is leaked.

If step 4 fails because of an exception, then the T1 object has been allocated and fully constructed, but the standard does not require that it be destroyed and its memory deallocated. The T1 object is leaked.

As I have mentioned that performing multiple operations in a single statement is potentially harmful. If you have no option and want to go the above way then the above mentioned problems can be avoided by the use of auto_ptr. See here.

Check out the book on Amazon:



Tuesday, 12 January 2010

Order of Evaluation of functions

Consider the following code:





//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>

using namespace
std;

class
Base{
public
:
Base():x(0){};
int
incrAndGetX(void) {return ++x;};
int
decrAndGetX(void) {return --x;};
int
x;
};


int
Add(int a, int b)
{

return
(a+b);
}


int
Sub(int a, int b)
{

return
(a-b);
}


int
main()
{

Base b;
int
val1 = Add(b.incrAndGetX(), b.decrAndGetX());
int
val2 = Sub(b.incrAndGetX(), b.decrAndGetX());

cout<<"Val 1 = "<<val1<<endl;
cout<<"Val 2 = "<<val2<<endl;

return
0;
}







What is the output of the following program?

Depending on the compiler the output can be different. I tried it using the g++ and MSVC8 compilers and got the same result but the result cannot be guaranteed. I got the following output:

Val 1 = -1
Val 2 = 1

As you will notice that the order of evaluation is from right to left. Depending on the compiler and the platform the order of evaluation could be left to right, right to left or interleaved. The kind of problem shown in the program above can be dangerous as your code will work on 99% of the PCs and will fail on 1% and you will invest lots of time and resources to find and fix the problem.

There is an interesting discussion here on the same topic if you want to explore this topic further.

Wednesday, 23 December 2009

Example of SetEnvironmentVariable and GetEnvironmentVariable

Sometimes you may want to communicate between different DLL's using some sort of flags. The simplest way to do it probably is using environment variable. Here is a simple example but can be modified to suit multiple DLL's.





//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>
#include<atlstr.h>

using namespace
std;

int
main()
{

//Suppose we want to have a temporary environment variable called "ZahidVar" whose value could be "120" or "140"
string varName("ZahidVar");
CString value;
DWORD len = GetEnvironmentVariable(varName.c_str(), value.GetBuffer(100), 100);
value.ReleaseBuffer();

if
(len)
cout<<"Value of environment variable = "<<value<<endl;
else

cout<<"environment variable was empty"<<endl;

//Set the environment variable now
SetEnvironmentVariable("ZahidVar", "120");

len = GetEnvironmentVariable(varName.c_str(), value.GetBuffer(100), 100);
value.ReleaseBuffer();

if
(len)
cout<<"Value of environment variable = "<<value<<endl;
else

cout<<"environment variable was empty"<<endl;

return
0;
}







The output is as follows:


It should be noted that the scope of this environment variable is temporary and will cease to exist once the program exits.

You can also look at this example to show you how to print all the environment variables.

Wednesday, 16 December 2009

BOOL to bool

I faced a very simple problem the other day. The compiler started generating a warning:

warning C4800: 'int' : forcing value to bool 'true' or 'false' (performance warning)

The reason being that because I was including some Windows file that included windef.h. In windef.h, it says: typedef int BOOL;

What I was trying to do was to cast that BOOL to bool. Of course we can suppress the warning easily by the #pragma directives as discussed earlier but there has to be a better and a simpler way. Then it clicked, how about a simple != 0 comparison. Here is the sample code:



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>
#include<windows.h>
#include<windef.h>

using namespace
std;

int
main()
{

BOOL someVal = 1;

bool
firstApproach = someVal; //Generates warning C4800
cout<<"firstApproach = "<<firstApproach<<endl;

bool
secondApproach = (someVal != 0); //No Warning
cout<<"secondApproach = "<<secondApproach<<endl;

return
0;
}

Wednesday, 9 December 2009

Catching the 'Divide By Zero' exceptions

I was surprised to find that C++ does not catch divide by 0 exceptions by default. The code will crash when a divide by 0 situation occurs. As a result the only option is to write our own class or method to handle divide by 0 scenario. The example below shows how to handle the Divide by zero scenario and how to construct an exception.







//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>

using namespace
std;

class
Division
{

public
:
double
quotient(int numerator, int denominator);
private
:

};


double
Division::quotient(int numerator, int denominator)
{

if
(!denominator)
{

exception e("Divide by 0 exception");
throw
(e);
}

return
(static_cast< double >( numerator ))/denominator;
}



int
main()
{

Division d;
try

{

cout<<"1. (100/10) = "<<d.quotient(100, 10)<<endl;
cout<<"2. (10/4) = "<<d.quotient(10, 4)<<endl;
cout<<"3. (10/0) = "<<d.quotient(10, 0)<<endl;
cout<<"4. (30/9) = "<<d.quotient(30, 9)<<endl;
}

catch
(exception& e)
{

cout<<"Exception caught with cause :"<<e.what()<<endl;
}

return
0;
}








The output is as follows:


You can read more on this topic here.

Wednesday, 2 December 2009

Using constants with functions

There always seems to be confusion in using const with functions. I am not referring to const functions that have const after the function name, that is straightforward. Also, the way functions behave when you have const before them is different than the built-in types. I have earlier provided a table for that.

Here is a simple program that shows different types of const with functions.



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>
#include<string>

using namespace
std;

class
A
{

public
:
int
x;
};


class
B
{

public
:
string y;
};


A* const createA()
{

return
(new A);
}


const
B* createB()
{

return
(new B);
}


int
main()
{

A* a = NULL;
a = createA();
a->x = 100;
cout<<"a.x = "<<a->x<<endl;
delete
a;

const
B* b = NULL;
b = createB();
//b->y = "Hello"; - Compilation error because b is constant
(const_cast<B*>(b))->y = "Hello";
cout<<"b.y = "<<b->y<<endl;
delete
b;

A* const a2 = NULL;
//a2 = createA(); - Compilation Error:
// you cannot assign to a variable that is const

A* const a3 = new A; //not possible to change what a3 points to now
a3->x = 23456;
cout<<"a3.x = "<<a3->x<<endl;
delete
a3;

return
0;
}






The output is as follows: