If you can change the signature of your function, then try changing it to
int EndsWith(char const * str, char const * suffix, int lenstr, int lensuf);
This will result in a safer, more reusable and more efficient code:
- The added const qualifiers will make sure you don't mistakenly alter the input strings. This function is a predicate, so I assume it is never meant to have side-effects.
- The suffix to compare against is passed in as a parameter, so you can save this function for later reuse with other suffixes.
- This signature will give you the opportunity to pass the lengths of the strings in if you already know them. We call this dynamic programming.
We can define the function like so:
int EndsWith(char const * str, char const * suffix, int lenstr, int lensuf)
{
if( ! str && ! suffix ) return 1;
if( ! str || ! suffix ) return 0;
if( lenstr < 0 ) lenstr = strlen(str);
if( lensuf < 0 ) lensuf = strlen(suffix);
return strcmp(str + lenstr - lensuf, suffix) == 0;
}
The obvious counter-argument for the extra parameters is that they imply more noise in the code, or a less expressive code.