macro


Hi all,

i have the following example
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

#define ADD(a,b) for(int i=0;i<100;i++) (a= b+i)

int main{
int a(0),b(0),c;

c= ADD(a,b);
cout << c;

return 0;

}


i can not compile this code because of the for statement-i guess-

how could for statment implemented in macro?
Last edited on
It isn't going to work.

Do you know what the preprocessor does?
It replaces all instances of what you defined with the value.
So this:
c= ADD(a,b);
is really:
c = for(int i=0;i<100;i++) (a= b+i);
after the preprocessor is done.

Also your return statement will not work. You need a space between the keyword and the '0'.
Last edited on
Why is there suddenly a slew of people posting silly macro questions?

Use a function.

1
2
3
4
5
6
int ADD( int a, int b )
  {
  for (int i = 0; i < 100; i++)
    a = b + i;
  return a;
  }

One thing to note: the function you wrote is the same as:
1
2
3
4
int ADD( int a, int b )
  {
  return b + 99;
  }

Also, if you intend for the argument values to be affected, you need to make them references:
1
2
3
4
5
int ADD( int& a, int b )
  {
  a = b + 99;
  return a;
  }

Et cetera.

Finally, watch your syntax. When programming, there is no room for ommissions or variations.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using namespace std;

int ADD( int& a, int b )
  {
  a = b + 99;
  return a;
  }

int main()
  {
  int a = 0;
  int b = 0;
  int c;

  c = ADD( a, b );

  cout << "a = " << a << endl;
  cout << "b = " << b << endl;
  cout << "c = " << c << endl;

  return 0;
  }

Hope this helps.
Topic archived. No new replies allowed.