0

I am attempting to convert this function as macro to reduce code line.

void gotoxy(int x,int y)    //cursor placing
    {
        COORD coord;
        coord.X =x;
        coord.Y=y;
        SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coord);
    }

What is the proper way to write this function as a macro? I have attempted this

#define gotoxy(x,y) COORD coord;coord.X = x;coord.Y = y ; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coord)

and it shows [Error] redeclaration of 'coord' with no linkage.

Ooi Eugene
  • 13
  • 3
  • 2
    Macros are the devils invention. You should convert macros *to* functions, not the other way around. – Some programmer dude Aug 02 '20 at 05:54
  • 2
    As for the goal "to reduce code line", don't. What you're trying to do is to make the code harder to read, understand and maintain. And source-code size have very little relation to the size of an optimized executable program. – Some programmer dude Aug 02 '20 at 05:59

1 Answers1

2

You need to bundle the statements into one scope using {}. The usual way to do this in a macro is the "do while(0)" trick:

#define gotoxy(x, y) do { \
    COORD coord; \
    coord.X = x; \
    coord.Y = y; \
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord); \
} while(0)

The {} scope allows you to introduce local variables. The "do while(0)" trick is explained here: do { ... } while (0) — what is it good for?

But you say you're doing this to reduce code lines, so here's a better way to achieve that strange goal:

void gotoxy(int x,int y){COORD coord; coord.X=x; coord.Y=y; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coord);}

Of course you should never write code in this style, but if someone is threatening to kill you if you don't reduce the number of lines of code in your project, the above will save your life.

Finally, we can see from the documentation that COORD is a struct containing just X and Y, so we can simplify this:

COORD coord;
coord.X=x;
coord.Y=y;

to this:

COORD coord{x,y};

That's two lines saved without selling your soul to the C preprocessor.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436