0

Well, I am learning C programming.Today I faced a problem while coding. I have made a string variable named,"answer". But when I wrote a condition, I found an error message but I don't know why. The code runs like this:-

if (answer == "something")

1

You can check for equality if it is a float a = 10.00; or int b = 10; or char c = 'a' or any other datatype variables like short,long, unsigned int but that is not the case for a string or char[] array, In C strings are stored as an array of characters char[] that means multiple characters in a single variable, when you write if( answer == "something"){...}, C understands the statement in a different way and that can be understood only if you know Pointers which will come later or after you learn basic programming techniques and concepts.

And also the error you are seeing is Compiler dependent For eg. clang C compilers generate warning like this

errors.c:36:21: warning: result of comparison against a string literal is unspecified (use strcmp instead)
    if (answer == "something") //WARNING HERE
                ^~ ~~~

For now, You just need to know that, In C direct string comparison using == operator is not possible, For that C provides you with a library function strcmp(string1, string2), return values of this function are 0-if strings are equal, 1- if string1 is greater than string2 and -1 if its another way around.

Here is cs50 manual for strcmp(s1,s2)

For that you have to include a Header file named string.h like below.

#include<stdio.h>
#include<string.h>
int main(){
   ...
   if(strcmp(answer,"something") == 0)
      printf("Equal\n");
   return 0;
}
| improve this answer | |
1

You're having problems because you can't use "==" to compare strings. You need to use a function call to strcmp() or maybe strcasecmp()

It's a very, very common mistake by new programmers. I even did it myself when I was learning. ;-)

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

| improve this answer | |

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .