Definition of Macros with C Indexing

0

Good afternoon, I would like to know if in C you have to do the following macro definition:

#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);
}
    
asked by anonymous 12.07.2017 / 20:48

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)))

Here is an example of how to use it:

#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;
}

Output:

idx=1 n=26
idx=2 n=15
idx=3 n=38
    
13.07.2017 / 16:27