6

I want to pass a macro as an argument in a C function, and I don't know if it possible. I would like to see this operation, for instance:

I have these macros:

#define PRODUCT(A, B) ((A) * (B)) 
#define SUM(A, B) ((A) + (B))

And then I have this function with the following signature:

int just_a_function(int x, MACRO_AS_PARAMATER_HERE);

and then i want to call this function like:

just_a_function(10, SUM);

is it possible?

Thanks

Anderson Carniel
  • 1,711
  • 2
  • 16
  • 22

5 Answers5

15

You can't pass as function argument.

But if function is a macro this is possible.

#include <stdio.h>

#define PRODUCT(A, B) ((A) * (B)) 
#define SUM(A, B) ((A) + (B))
#define JUST_A_FUNCTION(A, B, MACRO) MACRO(A, B)

int main() {
        int value;

        value = JUST_A_FUNCTION(10, 10, SUM);
        printf("%d\n", value);

        value = JUST_A_FUNCTION(10, 10, PRODUCT);
        printf("%d\n", value);

        return 0;
}
TheOliverDenis
  • 522
  • 6
  • 18
4

You can't do that.

Use normal functions instead:

int sum(int x, int y)
{
    return x+y;
}

//...

just_another_function(10, sum);

Note: just_another_function must accept int (*)(int, int) as the second argument.

typedef int (*TwoArgsFunction)(int, int);
int just_another_function(int x, TwoArgsFunction fun);
milleniumbug
  • 15,379
  • 3
  • 47
  • 71
0

Hi what you are passing is macro means its a substitution your passing . Think about it .. Ex : #define HIGH 1 In a function you can use int variable. So you can pass 1 to the function . In a function its stored as integer variable

0

Preprocessor directive works first . Once in a main macro are replaced means in the sense in a function you have to take care of the substitution. If I would have used Macro High 1 ,, in function I will take as int as a argument to get for local function stack. For better understanding check the topics 1.preprocessor directive 2. How the hex file created once you will compile

0
#include <stdio.h>
#define HIGH 1
#define LOW 0

void pin(int, int);

void pin(int a, int b) { 
  printf("A: %d B: %d\n", a, b);
}

int main() {
  pin(1, HIGH);
  return 0;
}

Compilation step involve:

  1. pre processor directive
  2. compiler
  3. linker
  4. executable file