How to correctly call a function through another function in C?

1

I have the following functions:

int testarDivisibilidade(int dividendo, int divisor);
int divisibilidade3(int num);

And the following variables:

int dividendo;
int divisor;

With the function testarDivisibilidade , I'll check if the dividendo is divisible by the divisor.

Code:

int divisibilidade3(int num)
{
    int res = 0;

    while( num > 0 )
    {
        res += num % 10;
        num /= 10;
    }

    if(res > 9)
        return divisibilidade3(res);
    else
        return ! (res % 3);

int testarDivisibilidade(int dividendo,int divisor) {

    if(divisibilidade3(dividendo) == 1) {
        printf("%d é divisivel por %d ", dividendo,divisor);
        return 1;
    }

    return 0;


}

I have to check if divisibilidade3 returns true so I can then fire the message inside the if. But this is giving problem, because for all cases of dividendo , it returns as true .

In short: How can I correctly check my function divisibilidade3 within function testarDivisibilidade ?

    
asked by anonymous 10.05.2017 / 17:50

1 answer

2

Note that the example code you posted does not compile:

  • First, on line 12, you are calling a function Divisibilidade() , when you certainly wanted to call divisibilidade3() (note the D uppercase and the lack of 3 ). / li>

  • Second, in the same line 12, you are calling the function and discarding the result : what you actually meant is return divisibilidade3(res); This causes the compiler to issue an error that "Not all code paths return."

  • Finally, in the base case of recursion, on line 14, you are returning res % 3 , which does not return 1 when num is divisible by 3 . Instead, you mean return res % 3 == 0; or return ! (res % 3);

With these changes, the divisibilidade3() call within testarDivisibilidade() is correct and should work.

Note that in testarDivisibilidade() function, you test whether dividendo is divisible by 3 using divisibilidade3() and, by issuing a message saying dividendo is divisible by divisor , to any value of divisor ! Strictly, this is wrong unless you pass 3 as an argument to the divisor parameter.

    
10.05.2017 / 18:49