Home > Blockchain >  Why does C allow to return a different type than the function return type?
Why does C allow to return a different type than the function return type?

Time:10-31

In this code, the multiply function's return type is char. Clearly, I'm returning a double value and printing with the double format specifier and it gives the appropriate value. If I try to print using the %c format specifier, it doesn't print anything. Either way, isn't it supposed to give an error?

#include <math.h>
#include <stdio.h>

char multiply(double x, double y)
{
return (double)(x * y);
}

int main() {
    double x = 10, y = 20;
    printf("%f", multiply(x, y));
}

CodePudding user response:

Actually, C does not allow this.

Clearly, I'm returning a double value and printing with the double format specifier and it gives the appropriate value

No, you do not return a value of type double. That value is converted to char before the function is left. This is called an implicit conversion.

Using format specifier %f requires a parameter of type double. Instead you pass a char which is promoted to int for variadic functions. This parameter mismatch causes undefined behaviour. If the result looks like you wanted it, that is just by accident.

If I try to print using the %c format specifier, it doesn't print anything.

You multiple 10*20. What result do you expect if you print the value 200? If your char is signed, then this overflows to a negative value. That is no valid ASCII value and probably nothing that is printable.

Either way, isn't it supposed to give an error?

At least you should get some warning. I am not sure about the implicit conversion but surely for the parameter mismatch in printf.

If you did not get one, turn up warning level. For GCC use -Wall -Wextra.

  • Related