0

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?

Nightowl
  • 69
  • 2
  • 6
  • 2
    You need the function prototype above `main`. And compile with warnings, please. – Eugene Sh. Nov 22 '17 at 18:05
  • Look up "forward declaration". If you are new to the language (especially for C or C++), it is a very important concept. – realharry Nov 22 '17 at 18:08
  • You're using a compiler that either uses the obsolete **28** year old C standard revision that was cancelled and replaced 18 years ago, or you're not reading the compiler warnings (which you should consider as **errors** and diligently copy into your question!). – Antti Haapala -- Слава Україні Nov 22 '17 at 18:11
  • Yes, thats actually a thing I could have done, sorry I'm in my first weeks learning C and totally forgot such an important rule. – Nightowl Nov 22 '17 at 18:13
  • And at first start with google and the diagnostics message! – Antti Haapala -- Слава Україні Nov 22 '17 at 18:16
  • @Antii Haapala That's a thing I considered doing before, however I thought my question had to do something with type promotion rules so after a longer time searching the web I thought posting a question would finally help me, and it did – Nightowl Nov 22 '17 at 18:21

1 Answers1

2

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

user2736738
  • 30,591
  • 5
  • 42
  • 56