1

I'm trying to make this program say good but it says okay instead though I made the variable value the same of the if test value

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

int main()
{
    char history[200];
    history == "NY school";

    if(history == "NY school")
    {
        printf("good");
    }
    else{printf("okay");}
    return 0;
}

4 Answers4

5

You need to use the function strcmp

i.e.

  if (strcmp(history ,"NY school") == 0) ....

Otherwise you are comparing pointers

Plus change

  history == "NY school";

to use strcpy

Ed Heal
  • 59,252
  • 17
  • 87
  • 127
2

This should work for you:

#include <stdio.h>
#include <string.h>
        //^^^^^^^^ Don't forget to include this library for the 2 functions

int main() {  

    char history[200];
    strcpy(history, "NY school");
  //^^^^^^^Copies the string into the variable
    if(strcmp(history, "NY school") == 0) {
     //^^^^^^ Checks that they aren't different
        printf("good");
    } else {
        printf("okay");
    }

    return 0;

}

For more information about strcpy() see: http://www.cplusplus.com/reference/cstring/strcpy/

For more information about strcmp() see: http://www.cplusplus.com/reference/cstring/strcmp/

Rizier123
  • 58,877
  • 16
  • 101
  • 156
1

Strings cannot be assigned (which would use a single =, not == as in your code). Look up the strcpy() function in the standard header <string.h>.

Also, strings (or any arrays, for that matter) cannot be compared using the relational operators (==, !=, etc) - such comparisons compare pointers (the address of the first element of the array) not the contents of the strings. To compare strings, use the strcmp() function, again in <string.h>.

Rob
  • 1,966
  • 9
  • 13
-1

With a bit of implementation defined optimiser luck this might work also:

#include <stdio.h>

int main(void)
{
  char * history = "NY school";

  if (history == "NY school") /* line 7 */
  {
    printf("good");
  }
  else
  {
    printf("okay");
  }

  return 0;
}

At least it works when being compiled by gcc (Debian 4.7.2-5) 4.7.2, with no optimisation btw.

The code shown above prints:

good

During compilation it however triggers the warning (for line 7):

 warning: comparison with string literal results in unspecified behavior [-Waddress]
alk
  • 69,737
  • 10
  • 105
  • 255
  • As other comments and replies have pointed out, strings cannot be compared using the == operator. It is necessary to use the strcmp() function (which is declared in standard header ). – Rob Feb 28 '15 at 12:25
  • @Rob: The code I show does not compare "strings", but pointers to them. – alk Feb 28 '15 at 12:26
  • 1
    That's right. The problem is that there is no guarantee whether those pointers are equal or unequal. – Rob Feb 28 '15 at 12:41