There is such a simple function to get the length of the line.

int stringLength(char *string,int result){ if(*string == 0){return result;} return stringLength(string+1,++result); } 

To return the result, I use another parameter that I need to pass in the call.

 int length = 0; length = stringLength(string,length); 

It is possible to make more beautiful, i.e. for example, a parameter that defaults to 0, and will not need to be specified when calling a function?

    3 answers 3

    Unusual use of recursion. In reality, this code is better to convert to a loop. But if the task is to use recursion, then you can hide the code from the user

     int length = 0; length = stringLength(string,length); 

    putting it in a function. For example:

     int stringLength(char *string) { int length = 0; return _stringLength(string,length); } int _stringLength(char *string,int result){ if(*string == 0){return result;} return _stringLength(string+1,++result); } 
    • By the way, she's tail. The compiler does the same loop? - Qwertiy
    • Maybe it will. But still, IMHO, the cycle would be read better here. - Jenyay

    There are no default parameters in C. But in C ++ there are:

     int stringLength(char *string, int result = 0) { 

      If you look at the declaration of the standard strlen function, which returns the length of a string, you can see that it is declared as follows

       size_t strlen( const char *s ); 

      Note that for example, a pointer has a const qualifier, which allows you to find the length of constant strings as well, and the return value is of type size_t .

      Therefore, the recursive function should be declared in the same way.

      Her definition is very simple.

       size_t stringLength( const char *s ) { return *s == 0 ? 0 : 1 + stringLength( s + 1 ); } 
      • But 1+ is no longer tail recursion and it may not become a cycle ... - Qwertiy