Reputation: 764
I develop a mac app using c++. I want to define the macro 'logi' corresponding to the call of two methods, so that method1()
and method2()
are being called. So I tried this:
#define logi method1 method2
It does not work. What is standard writing of this situation? thanks a lot!
Upvotes: 0
Views: 88
Reputation: 25536
At very first: If you can, avoid macros. If it is about calling two functions in a sequence, prefer defining an inline function instead:
inline void logi()
{
method1();
method2();
}
While inline
just is a recommendation for the compiler – and it might choose not to do so – for such simple functions you won't find any compiler not following this recommendation (rather would the function be inlined even without keyword).
This approach is much safer – and anything you do wrong the compiler will show you right at the function definition.
If you insist on a macro: Best practice is letting it look like a function, if it behaves like such one, as in your case:
#define logi() do { method1(); method2(); } while(false)
The loop wrapping around makes this macro robust if used like a function somewhere in code, imagine it was used without like that:
if(someCondition)
logi();
Guess, method2
would get called unconditionally (well, another example showing why it's good practice always to place braces around branch and loop bodies...).
The colon is skipped deliberately, so the user is forced to place it, again making the macro behave like an ordinary function.
Be aware that for macros the pre-processor does nothing more than simple text replacement. So whatever you define, it must be valid C++ code (to be precise: the outcome, when the pre-processor is done, must be valid code). How would a macro look like, if you needed to pass arguments to your functions? Well, you need to include them in the macro definition, too:
#define logi(A1, A2, B1, B2, B3) do { method1(A1, A2); method2(B1, B2, B3) } while(false)
Upvotes: 2
Reputation: 1039
I guess you only forgot the ';' between the two functions. Therefore that the #define
-macro only is a text-replacement in your code you need to 'end' the call of your function with a ';'.
But you might want to overthink using the #define
-macro that way. It does not seem to make much sense to me to do it this way. See here on "when to use #define
"
#include <iostream>
#define logi fun1(); fun2();
void fun1(void)
{
std::cout << "fun1 called\n";
}
void fun2(void)
{
std::cout << "fun2 called\n";
}
int main(void)
{
logi
return 0;
}
Upvotes: 0