I have one C++ define statement as:
#define PING 10
In my main function, I have something like:
int main()
{
int code;
cout<<"enter command code";
cin>>code; // value entered 10
cout<<code; //here i want "PING" output instead of 10
return 0;
}
How can I replace 10 with PING in my output?
Edit:
i will have multiple #define as
#define PING 10
#define STATUS 20
#define FETCH 74
#define ACK 12
#define TRAIL 9
#define EXIT 198
now my bussiness logic will get only command code i.e 10 or 12 etc etc
i want to retreive corresponding command name for that code..how is it possible??
How about replacing:
with:
That’s the easiest way if you have a single
#define. For more complicated cases, you could have an array of strings to look up, based on the#definevalues, something like:If the values are disparate, you can opt for a non-array-based solution, such as:
The other thing you may want to consider doing is replacing
#definevalues with enumerated constants. It may not matter for simple things like this but the type safety and extra information provided will almost certainly ease your debugging efforts at some point in your career.Nowadays, I generally only use
#definefor conditional compilation. Constants are better done with enumerations and it’s been a long time since I could out-think compilers on what should and shouldn’t be an inline function 🙂