Search code examples
cfunctionargumentsparameter-passing

Is it possible in C to make a function take two different data-types of variables as argument?


int count_letters(string text, int length);
int count_words(string text);
int count_sentences(string text);

void final(int letters, int words, int sentences);

int main(void)
{
    string text = get_string("Text: \n");
    int length = strlen(text);
   //printf("%i\n",length);

    int letters = count_letters(text, length);

Here I need variable "length" in all these four functions but all these functions already have a string type parameter.Is it possible to pass different types of parameters in a function?

Basically I want to know if this is correct (line 1 and line 13) and if no then how can i use this length variable in all these functions without having to locally define it in each function?


Solution

  • C strings are null character terminated. You do not need to pass the length of the string to the function. You need to iterate until you reach this character

    Example:

    int count_letters(string text)  //better to return size_t
    {
        int result = 0;
        for(int index = 0; text[index] != '\0'; index++) 
        {
            if(isalpha((unsigned char)text[index]))
            {
                result += 1;
            }    
        }
        return result;
    }