PresidentRFresh
PresidentRFresh

Reputation: 93

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.

Upvotes: 6

Views: 26193

Answers (4)

Roman Nikitchenko
Roman Nikitchenko

Reputation: 13046

Just stop thinking about macro like compilable code. Macros are "resolved" by pre-processor, not actually during compilation stage. So by macro definitions you just define how to process certain string in text file. Only output of pre-processor is passed to compiler. You can use gcc -E to see your source after pre-processor. It is still C code on this stage but without any preprocessor directive.

Hope this will help you.

Upvotes: 7

LihO
LihO

Reputation: 42133

#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;
}

Upvotes: 13

Graham Borland
Graham Borland

Reputation: 60701

What the compiler actually sees, after preprocessing, is:

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

The parameters passed to the macro are substituted into the body of the macro.

Upvotes: 5

MOHAMED
MOHAMED

Reputation: 43578

try to build your code with the gcc -E and see how your code look before compiling it

In fact in the build process the compilator transform your actual code to a preprocessor code. In the preprocessor phase the compilator replace all macro in your c code with its content and generate another code called preprocessor code and then the compilateor generate the object code from the preprocessor code

The gcc -E allow you to see your preprocessor code

Upvotes: 4

Related Questions