mercredi 11 mars 2020

use of #if in macro

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?

note: I'm using IAR 8.20.2

Aucun commentaire:

Enregistrer un commentaire