Thread: strstr doesn't return FALSE for empty string

  1. #1
    carpe diem
    Join Date
    Jan 2010
    Posts
    46

    strstr doesn't return FALSE for empty string

    I have an if statement with the following condition:

    Code:
    if ((strstr(to_units, param_units))&&(param_units!=NULL))
    {
    ...
    stuff
    ...
    }
    And the contents of my strings are:
    to_unit = "RADIANS"
    param_units= "" //param_units is empty

    "Stuff" is still getting executed even though param_units is empty. How do I make it so that the statement won't execute if param_units is empty?

  2. #2
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,834
    Code:
    if (param_units[0] && strstr(to_units, param_units))
    Note that I check for non-empty param_units first, so that the more time consuming strstr() does not get executed if it doesn't have to. And I forgot what bizarre result strstr gives when looking for empty string. I'm sure it's not intuitive. So I'd rather not take that risk.
    Last edited by nonoob; 07-09-2010 at 04:03 PM.

  3. #3
    Registered User
    Join Date
    Jun 2010
    Location
    Michigan, USA
    Posts
    143
    According to the C99 standard (7.21.5.7 p3) , strstr returns the first parameter if the second parameter points to a zero length string.

  4. #4
    carpe diem
    Join Date
    Jan 2010
    Posts
    46
    thanks nonoob! I used your code and it works perfectly.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Unable to compare string with 'getter' returned string.
    By Swerve in forum C++ Programming
    Replies: 2
    Last Post: 10-30-2009, 05:56 PM
  2. Quick Ques on String Manipulation
    By ckuttruff in forum C Programming
    Replies: 8
    Last Post: 06-22-2008, 09:32 PM
  3. Replies: 8
    Last Post: 04-25-2008, 02:45 PM
  4. 6 measly errors
    By beene in forum Game Programming
    Replies: 11
    Last Post: 11-14-2006, 11:06 AM
  5. Alegro closes out on me
    By campsoup1988 in forum C++ Programming
    Replies: 8
    Last Post: 04-03-2006, 10:40 AM