Let's try to run the following code:
#include <stdio.h>
#define MY_MACRO1(isArray,y) do { \
if(isArray) \
printf("%d", y[0]); \
else \
printf("%d", y); \
}while(0)
int main()
{
int a = 38;
int b[]={42};
MY_MACRO1(0,a);
return 0;
}
it returns the error:
main.c: In function ‘main’:
main.c:12:39: error: subscripted value is neither array nor pointer nor vector
printf("%d", y[0]); \
Ok, so we would need a #if statement to run y[0] only if the variable is an array:
#define MY_MACRO2(isArray,y) do { \
#if isArray \
printf("%d", y[0]); \
#else \
printf("%d", y); \
#endif \
}while(0)
int main()
{
int a = 38;
int b[]={42};
MY_MACRO2(0,a);
return 0;
}
But it returns :
main.c:11:28: error: '#' is not followed by a macro parameter
#define MY_MACRO2(isArray,y) do { \
Is there anyway to call a #if statement inside a macro? if not, how can I do such a thing?
note: I'm using IAR 8.20.2
(this link does not help)
I you want to know why I would not like to use 2 different macros is because I need to to something like this (pseudo-code):
myFunction(int or array):
doSomethingWhereIntAndArrayBehavesDifferentlyLikePrintf();
doSomethingelse();
doSomethingelse();
doSomethingWhereIntAndArrayBehavesDifferentlyLikePrintf();
doSomethingelse();
- It is pretty handy : you can factorize code.
- It's a way of implementing polymorphism.
- It mimics the C++ template feature.
Not possible.
You could use C11 _Generic:
Sum up and another works around using VLA & macros.
Using _Generic
pros:
cons:
Using VLA (no ##)
pros:
cons:
Using VLA + ## (string concatenation macro)
pros:
cons:
macro ## without VLA:
pros:
cons:
Let me first say that I don't think you should use macro for this. You should have 2 separate functions instead, with possibly additional
_Generic
expression as shown in Lundins answer.However, it is possible to do with multiple macro defines:
You can use
BOOST_PP_IF
:See it live on Coliru