Search code examples
cfloating-pointtype-conversiontype-promotion

I'm still new to C and I dont have a clue why my float result is random (maybe type promotion rules?)


I believe that it has something to do with type promotion rules, but I'm not sure and considering the fact that I'm still new to programming, I cant imagine why this:

#include <stdio.h>

int main() {

    float result;
    result = function(2.4, 4.9);

    printf("Test: %.2f\n", result);
    system("PAUSE");
    return 0;
}

float function(float value1, float value2) {
    float calculation = value1 * value2;
    return calculation;
}

would print out

Test: -858993472.00

I'm typing in float values and I want my calculation to return an other float value as my result, what am I doing wrong?


Solution

  • Declare the function before you invoke it. Here you need to put the definition above main() or just put a declaration before main.

    #include <stdio.h>
    
    float function(float value1, float value2) {
        float calculation = value1 * value2;
        return calculation;
    }
    int main() {
    
        float result;
        result = function(2.4, 4.9);
    
        printf("Test: %.2f\n", result);
    
        return 0;
    }
    

    Or

    #include <stdio.h>
    
    float function(float value1, float value2);
    int main() {
    
        float result;
        result = function(2.4, 4.9);
    
        printf("Test: %.2f\n", result);
    
        return 0;
    }
    float function(float value1, float value2) {
        float calculation = value1 * value2;
        return calculation;
    }
    

    Also if you have turned on the warning then you will possibly see a message like this

    ..: 'function' was not declared in this scope