2

I want to call a particular function according to the value i passed to the macro. But it is giving me compilation error

#include <stdio.h>

#define calling(m, j) execcall ## m(j);

void execcall0 (int x) {
    printf("called 0 with arg %d\n", x);
}

void execcall1 (int x) {
    printf("called 1 with arg %d\n", x);
}

void execcall2 (int x) {
    printf("called 2 with arg %d\n", x);
}

int main () {
    int i = 0;
    for (i = 0; i < 3; i++) {
        calling(i, 1);
    }
}

Compilation error:

In function `main':
new.c:(.text+0x7a): undefined reference to `execcalli'
collect2: ld returned 1 exit status

Is it even possible whatever i am trying?

5
  • 6
    This won't work - macros are a compile-time thing - they are evaluated by the preprocessor. Use function pointers to get the behaviour you are looking for here. Commented May 13, 2014 at 11:34
  • 1
    use a switch-case or something similar instead. Commented May 13, 2014 at 11:36
  • @Theolodis actually it is a small picture.. in a real test case i am having thousands of function.. Is switch case/if else would be a faster approach? Commented May 13, 2014 at 11:38
  • 2
    Don't use a switch statement - use an array of function pointers. Commented May 13, 2014 at 11:38
  • thanks all for the answers.. Commented May 13, 2014 at 12:45

2 Answers 2

3

If you want to call a function based on the value of an integer you're better off writing an array of pointers to your functions, and indexing into the array using your integer.

void execcall0(int x); 
void execcall1(int x); 
void execcall2(int x); 

/* Array of pointers to void functions taking an int parameter. */
void (*apfn[])(int) =
{
    execcall0,
    execcall1,
    execcall2, 
};

int main()
{
   int i;
   for (i = 0; i < 3; ++i) {
      (apfn[i])(1);
   }
}

Remember to check the boundary conditions before you index!

Sign up to request clarification or add additional context in comments.

Comments

2

You can use an array to store functions, and modify the macro:

#include <stdio.h>

#define calling(m, j) exec_funcs[m](j)

void execcall0 (int x) {
    printf("called 0 with arg %d\n", x);
}

void execcall1 (int x) {
    printf("called 1 with arg %d\n", x);
}

void execcall2 (int x) {
    printf("called 2 with arg %d\n", x);
}

void (*exec_funcs[3])(int) = { execcall0, execcall1, execcall2 };

int main () {
    int i = 0;
    for (i = 0; i < 3; i++) {
        calling(i, 1);
    }
}

But then you don't really need a macro.

1 Comment

thanks. nice workaround.. works perfectly.. i will benchmark all the answers and suggestions and will share the results...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.