Thread: search for int in an array always 'found"

  1. #1
    Registered User
    Join Date
    Sep 2004
    Posts
    99

    search for int in an array always 'found"

    Hi, guys. I wrote this function, and I am having problems with it. It is supposed to search for an int specified by user in main(). However, it always returns '1', as "found"... Why is that?
    Here it is.
    Code:
    int search_array( int array[], int size, int search )
    {
       int flag, i; 
       flag = 0;
    
       for( i = 0; i < size; i++)
           {
            if (array[i] == search )
               {
                flag = 1;
                break;
               }
           }
    
    return flag;
    }
    Thanks in advance for enlightening me...

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >However, it always returns '1', as "found"...
    Maybe the int you were searching for was in the array. Post a full program that shows this function returning 1 when it shouldn't.
    My best code is written with the delete key.

  3. #3
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    My own test program worked correctly. I would imagine it more of a problem in how you are using it.

  4. #4
    Registered User
    Join Date
    Sep 2004
    Posts
    99
    It's kinda long. Let me cut out the piecies which reference to the function then.
    Code:
    main()
    {
       int search, flag, i;
       int array[SIZE];
       int copy_array[SIZE]={0};
       float average = 0;
       float midrange = 0;
       char choice;
    
    
       fill_array(array, SIZE);
       
       
    
       do
       {
          array_menu();
    
         scanf("%c",&choice);
    
    
          switch(choice)
          {
          /* cut out */
          case '5': 
    	{
    	 printf("What number are you looking for?\n");
                     scanf("%d", &search);
    	 search_array(array, SIZE, search);
    	        if( flag = 1 )
    	           printf("The value was found.\n");
    	        else printf("Sorry, not found.\n");
    	}
          break;
          case '6': insertion_sort(copy_array, SIZE);
          break;
          case '7': fill_array(array, SIZE);  
    
                    for ( i = 0; i < SIZE;  i++ )
                        copy_array[i] = array[i];
          break;
          case '0': return 0;
          break; 
          default: printf("Wrong choice! Bye\n"); 
                   return 0; 
          break;      
          }
       }
       while( getchar() != '0' );
    
    
       return 0;
    }
    
    
    /**************************************************/
    /* function definitions                                */
    /**************************************************/
    /* cut out */
    
    /*************************************************/
    /* this function searches for specific number      */
    /* in the array                                    */
    /************************************************/
    int search_array( int array[], int size, int search )
    {
       int flag, i; 
       flag = 0;
    
       for( i = 0; i < size; i++)
          {
              if (array[i] == search )
                {
                 flag = 1;
                 break;
                }
         }
    
    return flag;
    }
    Is this better?

  5. #5
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >if( flag = 1 )
    flag is now 1. It will continue to be 1 as long as you use = instead of ==.

    By the way, shouldn't it be
    Code:
    flag = search_array ( array, SIZE, search );
    ?

    [edit]
    I think that was my fastest bug find ever. It took me all of the time to scroll down to the code before spotting two problems.
    [/edit]
    Last edited by Prelude; 11-20-2004 at 09:37 PM.
    My best code is written with the delete key.

  6. #6
    Registered User
    Join Date
    Sep 2004
    Posts
    99
    Oh, man! I knew, I did it again! Thanks for pointing it for me.... I really need to work on my problem with assignment and equality in condition brackets.
    Anybody knows about a compiler who sends a warning message when you do that? I was told that some do, but I haven't found any yet.
    And, yes, it would be way better if I wrote flag = search_array (...) Thanks again.
    Blushing all over.....

  7. #7
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    gcc does:
    Code:
    itsme@itsme:~/C$ cat warning.c
    int main(void)
    {
      int flag = 1;
    
      if(flag = 2)
        return 1;
      return 0;
    }
    itsme@itsme:~/C$ gcc -Wall warning.c -o warning
    warning.c: In function `main':
    warning.c:5: warning: suggest parentheses around assignment used as truth value
    itsme@itsme:~/C$
    Doing if((flag = 2)) overrides the warning, but it's caught every single one of those mistakes I've ever done.

    Edit: As an alternative, consider changing your habits so the constant is on the left side as in if(2 == flag). Because if you make a mistake then if(2 = flag) is an error and must be caught by every compiler since 2 can't be used as an lvalue.
    Last edited by itsme86; 11-20-2004 at 10:32 PM.
    If you understand what you're doing, you're not learning anything.

  8. #8
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > Edit: As an alternative, consider changing your habits so the constant is on the left side as in if(2 == flag).
    Whilst it seems like a good idea, I dislike it for several reasons.

    1. It renders the code unreadable, at least by normal English parsing rules. It looks more like something out of Monty Python "3 is the number thy shall count to".

    2. If you have
    if ( myfunc() == 2 ),
    you'll get an error anyway with if ( myfunc() = 2 ), so swapping them does not make it any better or worse (except readability)

    3. if you have
    if ( var1 == var2 )
    then your safety net is blown away and you then have to rely on actually knowing the rules (or a good compiler). No amount of swapping the order will save you.

    4. It only actually applies to == vs. =
    I've seen proponents of this "trick" blindly turn
    if ( x < 3 )
    into
    if ( 3 < x )
    Which is so obviously broken, but because they got the "constant on left, code is good" idea stuck in their head, they didn't look past it to see what they were actually saying.

  9. #9
    chococoder
    Join Date
    Nov 2004
    Posts
    515
    > Edit: As an alternative, consider changing your habits so the constant is on the left side as in if(2 == flag).
    Whilst it seems like a good idea, I dislike it for several reasons.

    1. It renders the code unreadable, at least by normal English parsing rules. It looks more like something out of Monty Python "3 is the number thy shall count to".
    It just takes some getting used to.
    When you're programming Java it (after some practice) becomes second nature, especially for string comparison.

    "".equals(someString) will return false in Java if someString is not initialised, while someString.equals("") will throw an exception.
    Simple reason being that if someString is null you can't call a method on it of course, while on an empty string you can call methods and equals will return false if the argument is null (unless of course you define different in your own classes).

    Placing the literal in front in comparisons for equals as shown here will also prevent errors where by mistake an assignment is done instead of a comparison. Instead of a (possible, depending on compiler flags and nicety) a warning you'll now get an error.

    Just about anything that turns runtime errors into compiler errors would be a good idea

    Of course as always you have to be pragmatic

  10. #10
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Any serious attempt at writing in C should include use of lint IMO
    This can catch a whole range of problems

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. binary search function on string array
    By gandolf989 in forum C Programming
    Replies: 6
    Last Post: 10-02-2007, 01:47 PM
  2. Template Array Class
    By hpy_gilmore8 in forum C++ Programming
    Replies: 15
    Last Post: 04-11-2004, 11:15 PM
  3. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 10:33 AM
  4. binary search in an array
    By brianptodd in forum C++ Programming
    Replies: 4
    Last Post: 11-12-2002, 02:05 PM
  5. Hi, could someone help me with arrays?
    By goodn in forum C Programming
    Replies: 20
    Last Post: 10-18-2001, 09:48 AM