For a homework assignment, I need to implement a function which takes a char *s and a char c and return the index of c if found, and -1 otherwise.
Here’s my first try:
int IndexOf(const char *s, char c) {
for (int i = 0; *s != '\0'; ++i, ++s) {
if (*s == c) {
return i;
}
}
return -1;
}
Is that an okay implementation, or are there things to improve?
EDIT Sry, didn’t mention that I only should use pointer-arithmetic/dereferencing, not something like s[i]. Besides, no use of the Standard Library is allowed.
Yours is perfectly fine, as far as it goes. You should also write a simple test program that tests for the first char, last char, and a missing char.
Piling on to the ‘other ways to do it’ group, here is one with no
break, a singlereturn, and showing off pointer arithmetic. But, beware: if I were grading your homework, I would grade yours higher than mine. Yours is clear and maintainable, mine needlessly uses ?: and pointer subtraction.The output of this program is: