Showing posts with label Macro. Show all posts
Showing posts with label Macro. Show all posts

Wednesday, 21 April 2010

Printing Debug information through Macros

This example shows probably one of the most useful case for using Macro's. Since Macro's are expanded before the code is compiled, debug information like filename and line number is available in the macro to be used.




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

using namespace
std;

#define PRINT_DEBUG_INFO \
cout<<__DATE__<<" "<<__TIME__<<": "<<__FUNCTION__<<", "<<__FILE__<<", "<<__LINE__<<endl;
//Note that __TIMESTAMP__ can be used instead of __DATE__ and __TIME__

void
func1(int* someNum)
{

if
(someNum)
{

//Perform normal operations here
int someVar=0;
}

else

{

//Abnormal scenario
PRINT_DEBUG_INFO;
}
}


void
func2(int *); //forward declaration of func2

int
main()
{

int
*x = NULL;
func1(x); //Creating exception scenario
func2(x); //Creating exception scenario

return
0;
}


void
func2(int* someNum)
{

try

{

//Normal case here
if(someNum)
*
someNum = 100;
else
throw
0;
}

catch
(...) //Abnormal case
{
PRINT_DEBUG_INFO;
}
}





The output is as follows:
Please note that in the above example, the __DATE__ and __TIME_ functions return the compilation date and time, not the current date and time. More details here.

To get the current execution date and time, see this example.

Tuesday, 25 August 2009

A Macro Pitfall Question

Assuming that two macros are defined in the following way
#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.