As arising from the comments to the question you are not allowed to use any library functions – thus you need to compare those strings manually (note that you cannot just compare the pointers, these might be arbitrary addresses, you need to compare what the strings point to!) – and as you even don't seem to be allowed to write a separate function you need to inline this code as well.
In general string comparison might look as follows (here still as a function):
int cmp(char const* x, char const* y)
{
for(; *x && *y; ++x, ++y)
{
if(*x != *y)
// first position where the strings differ:
// x < y lexicographically if *x < *y, thus *x - *y < 0
// x > y analogously, so:
return *x - *y;
// this gives you the equivalence: x # y <=> cmp(x, y) # 0
// with # being any comparison operator
}
#if 0
if(*x)
return 1; // x is longer, thus x > y
if(*y)
return -1; // y is longer, thus x < y
return 0; // both equal
#else
// actually, as the null terminator is smaller than any other character
// anyway, we still can simply:
return *x - *y;
#endif
}
Edit: An even simpler solution (thanks @Lundin for the hint) just iterates as long as the strings yet can be equal:
while(*x && *x == *y) // covers *y being 0, too!
{
++x; ++y;
}
return *x - *y;
Side note: There's an issue with the comparison if your strings include values in the upper half of the character range (from 128 up to 255 inclusive; not an issue with your example): It is unspecified if raw char
is signed or unsigned – which makes a difference on comparing characters not residing in the same half of the range of char
(200 - 100 = 100 > 0
<-> -56 - 100 = -156 < 0
). You can achieve more consistent behaviour over different platforms if you cast to unsigned char
at any difference or comparison (above and below):
return static_cast<unsigned char>(*x) - static_cast<unsigned char>(*y);
Using such a function is, in general, the solution to prefer. Maybe you ask once more if you are allowed to write a new function after all!
Otherwise in your case you could reduce the code for testing on being smaller only, so:
char const* cur = str[j];
char const* min = str[k];
while(*cur && *cur == *min)
{
++cur; ++min;
}
if(*cur < *min)
{
// cur is lexicographically smaller or shorter than min!
// -> found a new minimum
k = j;
}