help with #define
Feb 12, 2019 at 8:49pm UTC
I need to do something like this:
#define ACTIVATE_MODE(x) mode#x();
void mode1();
void mode2();
int main(){
int i;
cin >> i; // i = 1
ACTIVATE_MODE(i)
return0;
}
so ACTIVATE_MODE(i) --> mode1();
Thank You!
Feb 12, 2019 at 9:13pm UTC
That's not possible with macros, but there are other alternatives:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
#include <iostream>
#include <stdexcept>
typedef void (*fp)();
void mode1();
void mode2();
void dynamic_mode(int i){
static const fp functions[] = {
mode1,
mode2,
};
static const size_t n = sizeof (functions) / sizeof (*functions);
i--;
if (i < 0 || i >= n)
throw std::out_of_range();
functions[i]();
}
int main(){
int i;
std::cin >> i;
dynamic_mode(i);
return 0;
}
Feb 12, 2019 at 9:21pm UTC
you can also just do this:
#ifdef use1 //set this in your project settings when you compile.
#define ACTIVATE_MODE(x) mode1();
#else
#define ACTIVATE_MODE(x) mode2();
Topic archived. No new replies allowed.