this is my first time playing with recursive functions, and this function that I wrote returns the size of a string if it contains only letters in ascending order, and if not it returns -1.
I don’t understand why it works for both codes, after I took out the second “return”. Is one more wasteful than the other? Would appreciate some insight.
with “return only_ascending_letters(string, index+1);”
#include <stdio.h>
int only_ascending_letters(char string[], int index);
void main() {
char string1[]="Hi my name is pete";
char string2[]="aabcdefg";
printf("the first string is %d and the second one is %d\n",only_ascending_letters(string1,0),only_ascending_letters(string2,0));
}
int only_ascending_letters(char string[], int index){
if(!string[index]) return index;
if(((string[index]>='a'&&string[index]<='z')||(string[index]>='A'&&string[index]<='Z'))&&((string[index]<=string[index+1])||!string[index+1]))
return only_ascending_letters(string, index+1);
else return -1;
}
with “only_ascending_letters(string, index+1);”
#include <stdio.h>
int only_ascending_letters(char string[], int index);
void main() {
char string1[]="Hi my name is pete";
char string2[]="aabcdefg";
printf("the first string is %d and the second one is %d\n",only_ascending_letters(string1,0),only_ascending_letters(string2,0));
}
int only_ascending_letters(char string[], int index){
if(!string[index]) return index;
if(((string[index]>='a'&&string[index]<='z')||(string[index]>='A'&&string[index]<='Z'))&&((string[index]<=string[index+1])||!string[index+1]))
/*Took out the return*/ only_ascending_letters(string, index+1);
else return -1;
}
Yes, you absolutely need the return. Note that C language rules are a bit lax about this issue, and if you hadn’t used the return value, it would be fine without it. However, you use the return value, so you need the return statement.
What you see is probably caused by the implementation detail that function on some architectures return (integral values) by setting a well known register to that value (eax on i386). Therefore, if the bottommost recursive call does
returnand set this register, and the calls in-between don’t stomp on that register, you see that it sort of works. However, you mustn’t rely on that.Note that good compilers will recognize this is a tail-recursive call and compile both variant basically the same way.