3

Can i compare#definevarible 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?

EsmaeelE
  • 2,331
  • 6
  • 22
  • 31
Rohini Singh
  • 297
  • 1
  • 14

2 Answers2

5

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).

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
  • In review I am asked to remove #define with static cost not sure why – Rohini Singh Sep 18 '17 at 15:10
  • some people don't like macros. In that case, `static const char *` is also OK, and maybe is even better since it guarantees that the memory of the string isn't duplicated. – Jean-François Fabre Sep 18 '17 at 15:12
  • @Jean-FrançoisFabre: Never use a macro if typesafe code will do as well (e.g. you will always get the same string, possibly save memory, etc.). – too honest for this site Sep 19 '17 at 11:58
  • yeah, in that case, you can avoid it without any copy/paste issue. Macros are great to avoid copying/pasting code constructs or token concatenation (to some extent) but here's it's overkill (I added such conclusion in my answer if you noticed) – Jean-François Fabre Sep 19 '17 at 15:59
2

No, there is no risk to comapre #define with char* at all.

    #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;    
    }
Aashish Kumar
  • 2,771
  • 3
  • 28
  • 43