Main suggestion
I would actually say length = strlen(s)
instead of length = strlen(s) - 1
.
This way, the variable's name reflects the variable's contents. For instance, strlen("abc")
is 3, so it is counter-intuitive to set length
to 2!
Of course you then need to set n = length - 1
and change your comparison to i < length
. This is a very natural way to do things in C. The following is a very common pattern:
int i;
int num_items = 5;
for (i = 0; i < num_items; i++) {
//will loop 5 times
}
Minor suggestions
- Consider renaming
i
and n
to something more meaningful like left
and right
Use constants for true and false to make your code easier to understand at a glance
#define TRUE 1
#define FALSE 0
//then you can return TRUE; or return FALSE;
Use assertions for quick and easy testing:
#include <assert.h>
...
void testPalindrome() {
assert(palindrome("") == TRUE);
assert(palindrome("a") == TRUE);
assert(palindrome("aA") == TRUE);
assert(palindrome("ab") == FALSE);
assert(palindrome("aba") == TRUE);
assert(palindrome("aab") == FALSE);
assert(palindrome("Abba") == TRUE);
//add several more
//try to think of cases that are likely to produce
//false positive or false negative results
}
int main(void)
{
testPalindrome();
//put the rest of your code here
...
}
This way as you make changes or improvements to your code, your tests will automatically run each time you run your program and you will notice if you accidentally break something. It also encourages you to think about how your function is actually supposed to behave. (E.g. is "" actually a palindrome? What about examples containing non-letters?)
palindrome("dead")
...? \$\endgroup\$