0

I have the following code:

int compare(string a,string b)
{
    int length=a.length();
    for(int i=0; i < length; i++)
    {
        if(a[i]<b[i])
            return 1;
        if(a[i]>b[i])
            return 0;
    }
    ....
}

I'm interesting in the cases when length of string a is bigger than length of string b and string a starts with string b.
Example:
string a="abcdefghi"
string b="abcde"
The function will return 0. I want to know if there is any chance for this function to return 1; in this conditions.

Ovidiu Firescu
  • 385
  • 3
  • 11
  • 3
    Written as it is, no. You should also consider `b.length` in the `for` loop. If you find yourself in the condition where one of the strings is over and you still have characters on the other, you know you have to return non-zero. – Federico klez Culloca Jun 28 '19 at 07:52
  • [Here](https://stackoverflow.com/questions/34873209/implementation-of-strcmp/34873406)'s a bunch of implementations in C which you can take inspiration from. – Federico klez Culloca Jun 28 '19 at 07:54
  • 4
    You're invoking undefined behavior, so anything can happen. `b[i]` is undefined when `i >= b.length()` – Sid S Jun 28 '19 at 08:13
  • Are you writing your compare function for the sake of it or do you just need to compare two strings? If it's latter case you just can write `a < b`. – sklott Jun 28 '19 at 08:35
  • I have a program that has a bug and I'm trying to find it (don't know the cases in which doesn't work and can't find a test where the program doesn't work but I know for sure that it has a bug) so I found this sequence of code and if this function can return 1 in this conditions that means this is one of the bugs. – Ovidiu Firescu Jun 28 '19 at 08:40
  • I wonder why you return 0 if a[i]>b[i] - and what about a[i]==b[i]? – JeffRSon Jun 28 '19 at 08:45
  • I didn't put the whole function and i just put random numbers on return because is not relevant to the question.I just wanted to know if it's possible to return 1 in this conditions. Here is the whole function https://pastebin.com/vduLJenZ and as you can see length will always have the length of a(pathPrev). – Ovidiu Firescu Jun 28 '19 at 08:52

1 Answers1

2

Total two scenarios are possible:-

  1. if we have the length of b > 0 , then we have to make sure that a[i] ASCII value must be less than b[i] ASCII value..

    string a="abcdefghi"
    string b="abcde"
    
  2. In your example when we reach at index 5, the result would be undefined, means b[5] might contain garbage value whose ASCII value is greater than a[i]. or the result might be vise-versa.

JeJo
  • 30,635
  • 6
  • 49
  • 88
sha111
  • 113
  • 1
  • 12
  • 1
    This is the answer I'm looking for, so in some cases in this conditions is possible for the function to return 1, thanks you. Also thanks to @Sid S for pointing out the same thing. – Ovidiu Firescu Jun 28 '19 at 08:43