Parvaneh
Parvaneh

Reputation: 1

## preprocessor operator and value of a variable

I have searched and seems it is not possible to do this in C using ## preprocessor operator.

I want to use a variable value and make a function name like MY_FUNC_3

I know that how to use '#define VALUE 3' and do this, but how I can do same with a variable.

#define PASTE(x,y) x ## y
#define function (func_name, value) PASTE(x,y)

int a= 3;

for (int a = 2; a < 10; a++)
{
    printf("%s\n", function(MY_FUNC, a))
}

Upvotes: 0

Views: 353

Answers (2)

alk
alk

Reputation: 70921

You cannot do that using the pre-processor, as it is invoke before compilation, so it does not know anything about possible run-time behaviour.

You could solve this using an array of functions, or more precise using an array of functions pointers, for example like this:

#include <stdio.h>

const char * function1(void)
{
  return "Result 1";
}

const char * function2(void)
{
  return "Result 2";
}

const char * function3(void)
{
  return "Result 3";
}

const char * (*functions[])(void) = {
  function1,
  function2,
  function3,
  NULL
};

int main(void)
{
  size_t i = 0;
  while (NULL != functions[i])
  {
    printf("function[%zu]: '%s'\n", i, functions[i]());
    ++i;
  }
}

Result:

function[0]: 'Result 1'
function[1]: 'Result 2'
function[2]: 'Result 3'

Upvotes: 1

SoronelHaetir
SoronelHaetir

Reputation: 15162

You can't do it with the preprocessor value holding a char, but you can do it like:

#define PASTE_(x, y) x ##y
#define PASTE(x, y) PASTE_(x, y)

#define value 3
void PASTE(FuncName, value)()
{...}

Upvotes: 0

Related Questions