For reasons that make sense to my application, I want to have a macro defined that will change “FOO=x;” to “BAR+=x;”. To do “FOO=x; BAR+=FOO;” would be horribly unwieldy, and would not work in this application. I have tried “#define FOO BAR+”, but I get a syntax error on the “FOO=x;” line. I have also tried “#define FOO= BAR+=”, but the equals sign is an invalid character in macro names. Is there some way to make this work my way, or am I going to have to do some other dirty work-around?
What is the intention of your code? Are you trying to set FOO and increment BAR? Or are you just trying to increment BAR through some sort of alternative interface?
FOO isn’t intended to be an actual variable… it’s just a macro, to make the the code significantly easier to understand for the kids I’m training. So, I guess I’m just trying to increment BAR through an alternative interface. Also, there may be a reason that I’ll want to change BAR to a different variable, so I only want to have to change it in one place.
How about this…
#define incr(var,n) ((var) += (n))
Then your code would look like…
incr(x,10);
incr(y,5);
This allows a single macro to increment whatever variable is passed to it.
From your original question, though, you seem to be wanting to hide the BAR variable from the user. Is there a reason for that?
If you want to hide the variable, how about
#define FOO(x) (BAR += (x))
When you use the macro, then you will write
FOO(5);
instead of
FOO=5
and the precompiler will output
(BAR += 5);
(I wont go into the whys for the seemingly excess parentheses. We can go into that in a separate thread if desired.)