Passing macros as arguments

I am need to pass #define macro as a definition.
Is there a way to do it? have typed a sample code for an idea i am trying to achieve .
I am not new to C++ but never worked much with macros..

//SAMPLE CODE
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#define UP "ifconfig  eth0 up"
#define DOWN "ifconfig eth0 down"

//function call 
func(UP);

//definition
void func(#define temp)//I know this is wrong 
{
 if (temp == UP)
   //execute UP
 else
   //dont execute
}


Any help is appreciated..
Not really, because macros are not part of the actual language, but are instead replaced before the compiler actually starts parsing the program logic.

That is... the compiler doesn't even see this:

 
func(UP);


It sees this:
 
func("ifconfig  eth0 up");


I won't get into the many many many reasons why you probably should not be using macros. But you can have a similar effect simply giving these a type:

1
2
3
4
5
6
7
8
9
10
const char* UP = "whatever";
const char* DOWN = "something else";

void func(const char* temp)
{
  if( temp == UP )
    something();
  else
    somethingelse();
}


However this also is problematic because:

1) It assumes all macros you pass to the function are const char*s.

2) If you have two macros that are identical you get undefined behavior (the compiler might differentiate them, or it might not -- depending on how optimized they are).


The safer way would be to just strcmp() the passed string:

1
2
3
4
5
void func(const char* temp)
{
  if( !strcmp(temp, UP) )
    something();
}



Or use the actual string class:
1
2
3
4
5
void func(const string& temp)
{
  if( temp == UP )
    something();
}


Both of these will work, but will not differentiate between two constants that are defined the same way.
you can use void* as argument type and then change its type to what you want (char* in this code)
Better way is to use Templates.
Macros preprocessed in the stage before compilation, so you are comparing temp with a char* type at this stage, which may cause compilation errors.
Thank you..
Topic archived. No new replies allowed.