简体   繁体   中英

I don't understand why this simple recursive function doesn't work in C

I'm trying to write a simple function for a larger assignment I am writing in C. The purpose of the function is to determine whether a string contains only lowercase or uppercase letters, and returns the size of the string (index of \\0) if it passes the test, and -1 if it doesn't. This is what i've written:

 #include <stdio.h>

int only_letters(char string[], int index);

void main() {
    char string1[]="Hi my name is pete";
    char string2[]="thisissupposedtobevalid";

    printf("the first string is %d and the second one is %d\n",only_letters(string1,0),only_letters(string2,0));

}

int only_letters(char string[], int index){
    if(!string[index]) return index;
    if(string[index]<'a'||string[index]>'Z') return -1;
    only_letters(string, index+1);
}

When I run this i am getting -1 for both the first string (which is supposed to be invalid) but also the second string, which is supposed to be valid.

(We're not allowed to use loops and we have a dozen other limitations, so please don't offer easier or simpler solutions, I know they exist but I am trying to understand why what I wrote doesn't work. )

Please turn on your compiler warnings, you're not returning anything from that function in the default case.

return only_letters(string, index+1);

Other problem is that you've got your range inverted. Capital letters have lower ASCII values than lowercase ones.

And main must return int . Not void .

This line has problems too:

if(string[index]<'a'||string[index]>'Z') return -1;

In the ASCII table, upper case letters come first, followed by several non-letter symbols, then the lower case letters. That line should look more like:

char l = string[index];
if(!((l >= 'A' && l <= 'Z') || (l >= 'a' && l <= 'z'))) return -1

Uppercase letters come before lowercase letters in ASCII. The first letter of your second string is a lower-case 't' with an ASCII value of 116. 'Z' on the other hand has an ASCII value of 90, thus 't' > 'Z'

ASCII(Z) == 90
ASCII(a) == 97
ASCII(t) == 116

尝试:

return only_letters(string, index+1); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM