Definition of Macros with Indexing in C

Asked

Viewed 61 times

0

Good afternoon, i wonder if in C has how to make the following definition of macro:

#define EXEMPLO(1)  a * c + b
#define EXEMPLO(2)  a + b + c
#define EXEMPLO(3)  b * c + a

And then use indexing in some code for example

for (x=1,x<4,x++)
{
  EXEMPLO(x);
}

1 answer

0


You can write your macro using ternary operators:

#define EXEMPLO(idx)  ((idx==1)?(a * c + b):((idx==2)?(a + b + c):((idx==3)?(b * c + a):0)))

Follow an Example of how to use:

#include <stdio.h>

#define EXEMPLO(idx)  ((idx==1)?(a * c + b):((idx==2)?(a + b + c):((idx==3)?(b * c + a):0)))

int main( int argc, char ** argv )
{
    int n = 0;
    int i = 0;

    int a = 3;
    int b = 5;
    int c = 7;

    for( i = 1; i < 4; i++ )
    {
        n = EXEMPLO(i);

        printf("idx=%d n=%d\n", i, n );
    }

    return 0;
}

Exit:

idx=1 n=26
idx=2 n=15
idx=3 n=38
  • Thank you for the reply!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.