Can i compare#define
varible andchar *
in strcmp as below.
#include<stdio.h>
#include<string.h>
#define var "hello"
int main()
{
char *p ="hello";
if(strcmp(p,var)==0)
printf("same\n");
else
printf("not same\n");
return 0;
}
Is there any risk comapre #define
with char *
as above example?
Don't trust us, trust the preprocessor output
File "foo.c"
#include <stdio.h>
#include <string.h>
#define var "hello"
int main(void)
{
char *buf="hello";
if(strcmp(buf,var)==0) // Is this good
printf("same");
return 0;
}
now:
gcc -E foo.c
lots of output because of standard system libraries then...:
# 5 "foo.c"
int main(void)
{
char *buf="hello";
if(strcmp(buf,"hello")==0)
printf("same");
return 0;
}
as you see your define has been safely replaced by the string literal.
When you have a doubt, just apply this method to make sure (more useful when converting to strings or concatenating tokens, there are traps to avoid)
In your case, you could also avoid the macro and use:
static const char *var = "hello";
which guarantees that only 1 occurrence of "hello"
is set (saves data memory).