Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Macro questions

Tags:

c

macros

On a software project (some old C compiler) we have a lot of variables which have to be saved normal and inverted.

Has somebody a idea how i can make a macro like that?

SET(SomeVariable, 137);

which will execute

SomeVariable = 137;
SomeVariable_inverse = ~137;

Edit:

The best Solution seems to be:

#define SET(var,value) do { var = (value); var##_inverse = ~(value); } while(0)

Thanks for the answers

like image 892
nuriaion Avatar asked Feb 06 '26 04:02

nuriaion


2 Answers

Try this

#define SET(var,value) do { var = (value); var##_inverse = ~(value); } while(0)

EDIT

Couple of links to the reason behind adding a do/while into the macro

  • https://stackoverflow.com/questions/257418/do-while-0-what-is-it-good-for
  • http://www.rtems.com/ml/rtems-users/2001/august/msg00111.html
  • http://c2.com/cgi/wiki?TrivialDoWhileLoop
  • http://blogs.msdn.com/jaredpar/archive/2008/05/21/do-while-0-what.aspx
like image 161
JaredPar Avatar answered Feb 08 '26 21:02

JaredPar


One hazard I haven't seen mentioned is that the 'value' macro argument is evaluated twice in most of the solutions. That can cause problems if someone tries something like this:

int x = 10;
SET(myVariable, x++);

After this call, myVariable would be 10 and myVariable_inverse would be ~11. Oops. A minor change to JaredPar's solution solves this:

#define SET(var,value) do { var = (value); var##_inverse = ~(var); } while(0)
like image 20
Fred Larson Avatar answered Feb 08 '26 20:02

Fred Larson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!