Reputation: 11
I've seen simple examples of macros, but wondering about something more complex, say with if statements and reassigning given variables. Can more complex expressions like this be done in a macro? I've got a function that'll be run billions of times, so it would nice to have the preprocessor just throw the code in there rather than passing variables back and forth.
Say I have the following function:
int foo(int a, int b, int c){
if (a > 2)
c = a;
if (b > 3)
c = b;
return a + b + c;
}
How can I make this into a macro?
Upvotes: 1
Views: 5455
Reputation: 156534
Note that macros aren't the same as function calls - macros actually replace the C source code where they are used instead of calling and returning - so there can be a lot of unexpected behavior! Your example could be made into a macro like so:
#define FOO(a,b,c)((a)+(b)+(((b)>3)?(b):((a)>2)?(a):(c)))
But again, there are many pitfalls when using complex macros, such as unclear operator precedence and duplicated auto-increment/decrement operators.
It's probably best to heed the advice of other answers and use alternative strategies than complex macros.
Upvotes: 3
Reputation: 47193
If it looks like it should be a function, then make it a function.
Compiler technology has become good enough over time, so you don't have to worry about stuff like this. Have trust in your compiler and you should be fine.
Upvotes: 1
Reputation: 213059
Easy - don't use macros - just use inline functions:
__inline int foo(int a, int b, int c)
{
if (a > 2)
c = a;
if (b > 3)
c = b;
return a + b + c;
}
Upvotes: 2
Reputation: 272657
Whilst you could replace your function with a macro, in all likelihood, it will make no difference to the performance. Any reasonable compiler will have moved the function inline if it it thinks it will help.
Upvotes: 1