简体   繁体   中英

How to define function as macro?

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.

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.

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