Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function like Macros in C

I am trying to understand the idea of function like Macros however there are a few points that befuddle me. For example say we have:

#define Max(a,b)  ((a)>(b)) ? (a):(b))

and I call it like such

int i = Max(4,5);

This will evaluate a conditional expression equivalent to a>b? If yes then a, else b. But I'm confused as to how the Max function knows what to do with the arguments. Unlike an actual function, the implementation isn't written in code in the calling program. is the statement to the right of the define statement doing this for me? Its just a new thing for me and I want to make sure I understand what is happening here.

This particular part of function like macros confuses me. I know that these types of macros are useful for reducing overhead costs since they exclude the JSR RTS processor instructions which saves memory on the stack.

like image 217
PresidentRFresh Avatar asked Mar 22 '13 16:03

PresidentRFresh


1 Answers

#define Max(a,b)  ((a)>(b)) ? (a):(b))

is a macro, that causes nothing else but a simple textual replacement within your code, which means that during the preprocessing this line:

int i = Max(4,5);

is changed into:

int i = ((4)>(5)) ? (4):(5));

Note that there is no type safety while working with macros like this one and you will have really hard time while debugging your code as well. Good rule of thumb is: Don't use macro when you can achieve the same with function:

int max(int a, int b) {
    return (a > b) ? a : b;
}
like image 189
LihO Avatar answered Oct 21 '22 22:10

LihO