Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

== doesn't works when comparing argv[] strings

I noticed that comparing a normal string variable with a string using strcmp and == operator both works, but comparing argv string using == doesn’t works, only it works with strcmp. why? What is so special?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char const *argv[]) {
    char *tempStr = "string";
    int x = atoi(argv[2]), y = atoi(argv[3]);
    
    if (strcmp(tempStr, "string") == 0) {
        printf("'strcmp' methods works in case comparing with normal string variable\n");
    }
    if (tempStr == "string") {
        printf("'strcmp' as well as '==', both the methods works in case comparing with normal string variable\n");
    }
    

    /* this works for argv[] strings*/
    if (strcmp(argv[1], "add") == 0) printf("%d", x + y);
    else if (strcmp(argv[1], "subtract") == 0) printf("%d", x - y);
    else if (strcmp(argv[1], "multiply") == 0) printf("%d", x * y);
    else if (strcmp(argv[1], "divide") == 0) printf("%d", x / y);
    
    // /* this doesn't works for argv[] strings */ 
    // if (argv[1] == "add") printf("%d", x + y);
    // else if (argv[1] == "subtract") printf("%d", x - y);
    // else if (argv[1] == "multiply") printf("%d", x * y);
    // else if (argv[1] == "divide") printf("%d", x / y);

    return 0;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

When you use ==, it compares the addresses, not the contents. You declared tempStr as a pointer to a string literal, and compared it to the same string literal. The compiler noticed that the literals are the same, so it used the same memory for both of them, and that made the addresses the same.

You can’t count on this being true, it’s a compiler optimization to combine these similar strings.

If you change the declaration to

char tempStr[] = "string";

you would not get the same result with ==. In this case, tempStr is a local array, while "string" is a static string literal, and they will be in different memory locations.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading