1

First a little code:

int counter = 0;

int get_counter() { return counter++; }

#define EVEN_OR_ZERO(cc) ( (cc) % 2 == 0 ? (cc) : 0 )

int next_even_or_zero = EVEN_OR_ZERO(get_counter());

This code might seem OK, but... Let's expand the macro:

int next_even_or_zero = get_counter() % 2 == 0 ? get_counter() : 0;

As you can see the macro will only return odd numbers - which is the opposite of what was expected (or desired).

The question: Is there any way to get this work as intended with a macro? Or is a regular function the only way to go?

//This works as wanted
int even_or_zero(int value) { return value % 2 == 0 ? value : 0; }
5
  • 2
    In C++ or in C? You've used both tags, which makes it very hard to know what answer you want. Commented May 3, 2015 at 10:57
  • 2
    In C++ at least, macro-functions like this are not a good idea. Commented May 3, 2015 at 10:58
  • 6
    The answer is simple: Don't use a macro, unless there's a good reason for it. This case isn't one of them. Commented May 3, 2015 at 10:58
  • It would help an awful lot to understand why you want a macro. Does it need to work for types other than int? Can we assume the parameter can be duplicated or captured? Etectera. Commented May 3, 2015 at 11:00
  • You are aware that get_counter() gets called twice, aren't you? Commented May 3, 2015 at 11:10

3 Answers 3

3
#define EVEN_OR_ZERO(cc) even_or_zero(cc)

This may be the perfect answer or a bad joke, depending on why you need a macro, which you haven't told us.

Sign up to request clarification or add additional context in comments.

Comments

2

The answer is simple: Don't use a macro, unless there's a good reason for it. This case isn't one of them:

int even_or_zero(int i) {
    if (i % 2) {
        return 0;
    } else {
        return i;
    }
}

1 Comment

... inline functions is the ticket here (assuming c++)
0

Make two functions.

int getCurrentCounter() { ... } // just return here
int getNextCounter() { ... } // increment here

This is how - in example - sequences is PSQL works.


Also, this seems like very bad code design.

  • don't use macros in C++, there are more better ways to achieve what you want (usally) without using them
  • functions with sideeffects on global variables are not that good. Think if it would not be better to create struct/class with it's counter and add methods to it. Or better yet, could hide methods as prive at set methods/class as their friends to limit who can affect counter.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.