Regarding: E.g. I have string ERROR_1000. It's a variable
:
If ERROR_1000 is defined as a string, the pre-processor #ifdef will not see it as "defined" eg:
char string[]="teststring";
int main(void)
{
#ifdef teststring
printf("%s", teststring);
#endif
return 0;
}
The printf()
statement will not execute because string is not recognized by #ifdef.
However, if you define it using #define teststring...
#define teststring "teststring"
int main(void)
{
#ifdef teststring
printf("%s", teststring);
#endif
return 0;
}
The `printf() statement will be executed.
Note, if you have a variable named "ERROR_1000". then you cannot also have a #define ERROR_1000. You would have to change one of them to use them together in the same code. eg: (the following will work)
#define ERROR_1000 "not defined"
char Error_1000[]="some other error message";
int main(void)
{
#ifdef ERROR_1000
printf("%s", Error_1000);
#else
printf("%s", ERROR_1000);
#endif
return 0;
}
Note also: statements used in C starting with #, such as #ifdef, or #define are all directives to the environment to preprocess or evaluate before running, or at compile time.
Statments such as if()
, or while()
are evaluated at run-time.
Regarding the latest edit to your post:
I think using the combination of #define
, #ifdef
and a switch()
statement, you can do what you want...
Maybe this will work for you?:
#define ERROR_1000
#define ERROR_3000
string fun(int id)
{
buf errorMsg[80];
sprintf(errorMsg, "ERROR_%d", id);
switch(id){
case 1000://this one will print
#ifdef ERROR_1000
printf("%s", errorMsg);
#endif
break;
case 2000://this one will NOT print
#ifdef ERROR_2000
printf("%s", errorMsg);
#endif
break;
case 3000://this one will print
#ifdef ERROR_3000
printf("%s", errorMsg);
#endif
break;
}
//here I got this number and create string "ERROR" + id, for example "ERROR_1000"
//so is it possible to check here, if there is a define with name ERROR_1000
//so if define exists return string from that define
}
Option without using switch()
(modify your function to use the #defines)
Perhaps some variation of this will work...?
#define ERROR_1000 "ERROR_1000" //will print
#define ERROR_2000 "" //will not print
#define ERROR_3000 "ERROR_3000" //will print
void fun(int id, char *print);
int main(void)
{
fun(1000, ERROR_1000);
return 0;
}
void fun(int id, char *print)
{
char errorMsg[80];
if(strlen(print)>0)
{
sprintf(errorMsg, "ERROR_%d is %s", id, print);
printf("%s", errorMsg);
}
}