SoniEx2
SoniEx2

Reputation: 2034

"resettable" loop DSL with C macros?

I want a loop to run once unless set to repeat, but I don't like the ugliness of having to explicitly set variables as part of normal program flow.

I'm using this but the project maintainers didn't like it:

int ok = 0;
while (ok^=1) {
    // ...
    if (something_failed) ok = 0;
}

(compare to while (!ok) { ok = 1; // ...)

The nice thing is that you can wrap these in macros:

#define RETRY(x) while (x^=1)
#define FAIL(x) x = 0

and use them as

int ok = 0;
RETRY(ok) {
    // ...
    if (something_failed) FAIL(ok);
}

How can I make these macros work without the weird xor-assign?

Upvotes: 0

Views: 93

Answers (1)

Lundin
Lundin

Reputation: 213721

Using XOR 1 to toggle something between 0 and 1 repeatedly is perfectly fine, particularly in hardware-related code. Is this what you are trying to do? But this isn't how you are using it, so it doesn't make sense. Also, using it together with a signed int is questionable.

Please don't invent some ugly macro language, that's 10 times worse! This is the worst thing you can do.

There exists no reason why you can't simply do something along the lines of this:

bool retry = true;
while(retry)
{
  retry = false;
  ...
  if(something_failed) retry = true;
}

Upvotes: 1

Related Questions