Search code examples
cfunctionvariablesfloating-pointreturn

Float function always returning 0.000000


I'm a beginner with C and I can't find the solution for this "error" ... (I don't want to just print what I read with scanf, that's just an extract from a bigger program, so can you try not to create a new code but to modify this ?)

Here's the code

#include <stdio.h>

float function(x){
    return x;
}

int main(){

    float x;
    scanf("%f", &x);
    printf("%f \n", function(x));

    return 0;
}

And if you don't mind ... can you explain the reason why it doesn't work in this way ? Thank you a lot


Solution

  • You defined your function as:

    float function(x){
        return x;
    }
    

    If you want the function to take a float argument, you need to say so:

    float function(float x){
        return x;
    }
    

    Fixing that should fix your problem. You don't really need to worry about why your incorrect program behaves the way it does.

    But if you're curious ...

    Prior to the C99 standard, C had an "implicit int" rule. In this case, the parameter x would be of type int because you didn't specify its type explicitly. But since you used an old-style definition, not a prototype, you haven't told the compiler that the argument should be of type int. (Yes, old-style function declarations and definitions can cause some serious problems. That's why we have prototypes.)

    So when you call your function with a float argument, the compiler doesn't complain, and it doesn't convert your argument from float to int. Instead, it promotes your argument from float to double (that's just one of the rules for calling a function with no visible prototype, or for calling a variadic function like printf), and the function itself assumes that you really passed it an int.

    Result: The behavior is undefined.

    One likely result is that the function will treat the double argument as if it were of type int, yielding garbage. Another is that it will read the int value from some other memory location or register, yielding even worse garbage.

    Always enable warnings. Always pay attention to any warnings your compiler produces. Always ask your compiler to conform to the C99 or C11 standard unless you have a specific reason not to. And always declare and define your functions with prototypes. (A prototype is a function declaration that specifies the types of the parameters.)

    This also means that int main() should be int main(void). That's not likely to matter (unless you call main recursively, which would be silly), but it's a good habit.