Wednesday, February 18, 2009

C++ Problem: Define that macro

I'm planning to post some C++ programming problems that I come across and shall post their solutions too (I'll try to post multiple solutions). Here goes the first one:

Problem:

DO_REPORTING is MACRO which when called at the start of a function with appropriate parameter, prints the value of the parameter at the start of the function and also somehow prints the value before leaving the function. For the following code expected output would be:

Before:2
After:4
Before:4
After:2

How would you get this output without changing anything in class A and inside main function?
  1 #include <iostream>
2 using namespace std;
3
4 #define DO_REPORTING(type,variable) ;
5
6 class A{
7 protected:
8 int val;
9 public:
10 A(int v){
11 val = v;
12 }
13 void FuncMult(){
14 DO_REPORTING(int, val);
15 val *= 2;
16 }
17 void FuncDiv(){
18 DO_REPORTING(int, val);
19 val /= 2;
20 }
21 int GetVal(){
22 return val;
23 }
24 };
25
26 int main(){
27 A a(2);
28 a.FuncMult();
29 a.FuncDiv();
30 return 0;
31 }
32
33

Solution 1:
  1 #define DO_REPORTING(type,variable) Report<type> r(val);
2
3 template <class T>
4 class Report{
5 T &val;
6 public:
7 Report(T &v):val(v){
8 cout << "Before:" << val << endl;
9 }
10 ~Report(){
11 cout << "After:" << val << endl;
12 }
13 };
14

3 comments:

luc said...

Very interesting. But (in my very humble opinion), you have to keep in mind that some new/novice readers are watching over your blogs and they might start copying this technique blindly without putting the #ifdef DEBUG clause. In the release build, if many functions create an object and destroys it just for debugging purposes, it might prove to be costly in some machines. So, May I , very humbly suggest you to keep these little things in mind (although it may not seem important) for the benefit of your readers.

luc said...

I actually assumed that, usually these types of utility macros are for debugging purposes (in most cases), so this is why I gave my opinion on this on the previous post.

Mohammad Kaisar Ul Haque said...

@luc: sorry for the long late reply. I thought I replied on this already :D.

Thanks for the suggestion. The post was basically a programming problem to examine one's skill with macro and object constructor/destructor. As you've mentioned, this can be used for debugging purpose but the post wasn't intended to show the debugging technique.

If this was shown as a debugging technique, yes, some more details and precautions would be required in the article. Thanks again.