Thread: comparing

  1. #1
    Registered User
    Join Date
    May 2002
    Posts
    17

    comparing

    hello guys,


    here is my problem


    main()
    {
    char st[]="hello";
    char str[]="hai";

    if (st==str)
    printf("bye");
    else
    printf("byebye");

    }

    here in the comparison in the if loop either the entire strings will be compared r the first character


    please expalin me

    bye
    srinu
    srinu

  2. #2
    Im back! shaik786's Avatar
    Join Date
    Jun 2002
    Location
    Bangalore, India
    Posts
    345
    >here in the comparison in the if loop either the entire strings will be compared r the first character
    1.) if is not a loop, it's a construct.
    2.) Neither the 'entire string' nor the 'first character' will be compared. You are only comparing the addresses where each of the strings(st[], str[]) are stored, and not the contents at those locations. Use 'strcmp()' instead.

  3. #3
    ....
    Join Date
    Aug 2001
    Location
    Groningen (NL)
    Posts
    2,380
    shaik786 is correct, you can't compare strings like that. You have to use a library function or compare each character by yourself. BTW, main() should return a value, it is of type int.

  4. #4
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >main()
    The correct way to define main with no arguments is

    int main ( void )

    >char str[]="hai";
    Looks harmless, right? Unfortunately this could break your program since identifiers starting with "str" are reserved by the implementation for future updates.

    >if (st==str)
    This test will always return false regardless of what the values in the arrays are. Note that the name of an array is a pointer to it's first element, so what you are doing with this test is checking two pointers to see if they point to the same address. Since they don't the test fails. If you want to check the entire string for equality of values you have to either loop through each element and test them by character or use strcmp:
    Code:
    if ( strcmp ( st, astr ) == 0 )
      printf ( "bye\n" );
    else
      printf ( "byebye\n" );
    -Prelude
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. comparing data in two files
    By nynicue in forum C Programming
    Replies: 25
    Last Post: 06-18-2009, 07:35 PM
  2. Replies: 2
    Last Post: 04-29-2009, 10:13 AM
  3. Problem with comparing strings!
    By adrian2009 in forum C Programming
    Replies: 2
    Last Post: 02-28-2009, 10:44 PM
  4. bit vs bytes when comparing a file
    By Overworked_PhD in forum C Programming
    Replies: 6
    Last Post: 05-19-2007, 11:22 PM
  5. comparing problem
    By Unregistered in forum C Programming
    Replies: 3
    Last Post: 03-05-2002, 06:19 AM