PDA

View Full Version : Basic C++ doubts



munna
5th April 2006, 16:46
// A macro that returns the absolute value of i
#define unsafe(i) \
( (i) >= 0 ? (i) : -(i) )

// An inline function that returns the absolute value of i
inline
int safe(int i)
{
return i >= 0 ? i : -i;
}

int f();

void userCode(int x)
{
int ans;

ans = unsafe(x++); // Error! x is incremented twice
ans = unsafe(f()); // Danger! f() is called twice

ans = safe(x++); // Correct! x is incremented once
ans = safe(f()); // Correct! f() is called once
}


Can someone please tell me why x is incremented twice and f() is called twice when i use unsafe(x++) and unsafe(f()) respectively ?

I also have an other doubt also.

I build a tree from a string. For Example: "a+bc+34" or "a+2+4"

I have two classes for this.

1.Literal
2.Value

and they inherit a class called "Node" which has a variable called "type : int"

Also I have two macros

#define LITERAL_OBJECT
#define VALUE_OBJECT

which helps me to find what type of node is and then type cast and then do some operation ( addition when the two nodes under plus are numbers...etc)

I think #define's are not needed at all but I am not able to figure out how to do away with them. Can someone pls tell me how can i do things in much better way?

Thanks a lot.

jacek
5th April 2006, 17:32
Can someone please tell me why x is incremented twice and f() is called twice when i use unsafe(x++) and unsafe(f()) respectively ?
Because:
ans = unsafe(f());will be changed by the preprocessor to:
ans = ( (f()) >= 0 ? (f()) : -(f()) );before the compilation.


I think #define's are not needed at all but I am not able to figure out how to do away with them.
Use virtual method that will return the type of the node. If each node would know what to do with its children you wouldn't need any casts.

Brandybuck
6th April 2006, 00:55
Do no mistake macros for functions. Preprocessor macros get expanded, not evaluated. The difference can be significant, as you have found out.

brcain
6th April 2006, 17:23
Good point, Brandybuck. I generally try to avoid macros altogether because of being burned in the past so many times.