Jump to content

Cpp Macro Function Problem

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
6 replies to this topic

#1
Egz0N

Egz0N

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 4,034 posts
hi there .. !!

i have a problem on C++ .. using Macro Functions ..

this is my code:

#include <iostream>
using namespace std;
#define test(x) ((x>4) ? (x + 3):(2*x-1))
int main()
{
double z;
int i;
for (i=1;i<3;i=i+1)
{
z = 2* test(i+2) + 4* test(1);
cout << "i="<< i
<<"\t Result:" << z
<< endl;
}
return 0;
}
and here's what the console application says:

Attached File  &#97;&#97;&#97;&#46;.JPG   10.83K   18 downloads

should the result be 14 and 18 .. what am i doing wrong .. :s ..??

#2
thechef

thechef

    Learning Programmer

  • Members
  • PipPipPip
  • 79 posts
I think the problem is in your define statement. Each x should be surrounded by parenthesis as in

#define test(x) (((x)>4) ? ((x) + 3):(2*(x)-1))

That way when the substitution for x in text(i+2) is made, it results in the following:

(((i+2)>4) ? ((i+2) + 3):(2*(i+2)-1))

Currently, it results in this:

((i+2>4) ? (i+2 + 3):(2*i+2-1))


#3
Egz0N

Egz0N

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 4,034 posts
ahhh .. thanks a lot mate .. :)

#4
ZekeDragon

ZekeDragon

    Writes binary right handed and hex left handed

  • Moderators
  • 2,103 posts
You've just experienced one of the big problems with macros, namely that they do NOT evaluate the expression like they do in a function, instead they just directly plug themselves in. So what you've basically got here when you say this:
z = 2 * test(i + 2) + 4 * test (1);
is this:
z = 2 * ((i + 2 > 4) ? (i + 2 + 3) : (2 * i + 2 - 1)) + 4 * ((1 > 4) ? (1 + 3) : (2 * 1 - 1));
The problem is where you have (2 * i + 2 - 1), since the 2 * i will evaluate before the i + 2, you have to place x in parenthesis in the macro like this:
#define test(x) (((x) > 4) ? ((x) + 3) : (2 * (x) - 1))
That should at least rectify this problem.

EDIT: cod3b3ast already got it. XD
Wow I changed my sig!

#5
Egz0N

Egz0N

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 4,034 posts
wow .. thanks zeke .. this helps too.. thanks a lot .. :)

#6
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
Just out of curiosity, why not just do this as an inline function, and avoid the problem with macros (evilness)?
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#7
Egz0N

Egz0N

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 4,034 posts
@WP: this was in a test i had a few days ago .. and i don't know if our professor made this with propose or this was a mistake of him :s .. otherwise i rarely use macro functions :s