Possible to use macros for a counter variable?

I tried:
1
2
#define counter_var 0;
++counter_var;

But I get error: non-lvanue in increment.
No. Go read up on how macros work and you will see.
macros are just a copy paste operation.

The compiler sees ++counter_var;, then notices that counter_var is defined as 0;, so it replaces counter_var with 0;, giving you this:

 
++0;;


which of course is nonsense. Hence the error.


Macros are evil, though. You really shouldn't use them unless you have no other option. They ignore scope rules, pollute the namespace, and lead to very cryptic errors. A normal variable will work just fine here.
is it bad to do:
1
2
3
4
5
6
7
8
9
using namespace std;
int error_counter = 0;
#define num_errors error_counter

int main()
{
    return ++num_errors;
}
WHYYYYYYY would you want to do that? You already have a variable, use it, what would you gain from using a macro?

And I quote

Macros are evil, though. You really shouldn't use them unless you have no other option. They ignore scope rules, pollute the namespace, and lead to very cryptic errors.
Last edited on
in a way, yes, because it pollutes the namespace and ignores scope rules.

1
2
3
4
5
6
7
#define foo bar

int main()
{
  int foo;
  int bar;  // the macro causes this to be a compiler error
}


Why can't you just use the variable name directly?
Topic archived. No new replies allowed.