Using #define

Hello,
I created a simple file to calculate a bisection and I had problems with the #define.

I used this structure:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#define __e 0.01 // define o erro
 #define f1x (pow(__x,2) - 5) // define F(x)
 #define f1a (pow(a,2) - 5) // define F(a)
 #define f1b (pow(b,2) - 5) // define F(b)
...
int main () 
{
	...
        bisseccao (__a, __b, __e, 0, i);
        return 0;
}

void bisseccao (long double a, long double b, long double e, int n, int i) 
{
	long double __x = (a + b) / 2, fa, fb;
	
	
	if (++n <= i && erro >= e) {
			fa = f1a;
			fb = f1b;
            ...
       }
  ....
} 

And in the function bisseccao () I have fa, a simple variable and I want that variable receive the result of the f1a ( defined on #define), but the result is wrong.
This is correct? If not, could some one help me, I need to do something like this, I need to inform the equation and calculate them.

Thank you,
GGarciaBas
That isn't quite right in principle. But rather than wasting time fixing that, as you're using C++, why not use functions? You can inline them if you feel you need them to be inline.
You can define them as a macro this way:
1
2
#define __e 0.01
#define f(a) (pow((a),2)-5) 


Then use them like so:
1
2
3
fa = f(a);
fb = f(b);
fx = f(__x);


But kbw is right, it's better to use functions than macros. Macros can cause some strange things.

Example:
using this macro:
#define max(a,b) (((a) < (b))?(b):(a))
like this:
max(i++, 0);
will give you this:
(((i++) < (0))?(0):(i++));
i get's incremented twice!
Last edited on
Thank you guys.
Can I get to the user's equation on running the program and use then to calculate a value of any number, I said, define the equation to the variable in the program execution?

GGarciaBas
Stewbond wrote:
You can define them as a macro this way:
1
2
#define __e 0.01
#define f(a) (pow((a),2)-5)  
Last edited on
Thank you.
Technically, __e cannot be used in a portable program, with or without a #define: it contains two underscores, and all such identifiers are reserved.
Topic archived. No new replies allowed.