简体   繁体   中英

Macros in C++ breaks with postfix increments

I need a working MAX macros (without(!) declaring main function) which assign 'r' the maximum of numbers 'a' and 'b'. This code breaks in compilation. How can it be fixed?

#define MAX(x, y, r) ((x) > (y) ? (r = x) : (r = y))

int x = 10;
int y = 20;
int r;

MAX(x, y, r);

Thanks for watching!

UPD: Some revision to clear the full task:

#import <iostream>
#define MAX(x, y, r) ((x) > (y) ? (r = x) : (r = y))

int x = 1;
int y = 1;
int r = 1;

int main()
{
    MAX(x++, y, r);
    std::cout << r;
    return 0;
}

The result of this code is 1, and need to be 2. So I need another logic in my macros to consider all postfix increments

You can't use this macro outside of a function, because it's an arbitrary expression, that's why you're getting an error.

Just move the invocation of the macro into function scope and it will work:

#define MAX(x, y, r) ((x) > (y) ? (r = x) : (r = y))

int x = 10;
int y = 20;
int r;

int main()
{
    MAX(x, y, r);
}

Using macros in this case is, however, unnecessary (unless this is just an exercise to learn macro usage); making max a function (or, better yet, using std::max ) would be a better and less error-prone way.

It doesn't work because you can't put arbitrary expressions at file-scope. I have a couple of suggestions:

  • Don't use global variables unless you really, really have to. They'll just cause you pain.

  • Don't use macros unless you really, really have to. They'll just cause you pain.

Here's what I'd do:

int main()
{
    int x = 10;
    int y = 20;
    int r = std::max(x, y);
    //pass x, y and r as arguments to functions rather than using globals
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM