Visual Studio not returning correct C float values

Viewed 840

I am doing some fairly simple math in visual studio 2019 with C, but floats are returning with incorrect values. While debugging I simplified the example down to just a quick return, but something is still off because there's no math included in my example. Is there something missing from my environment?

NOTE: I can return integers with no problem.

#include <stdio.h>

int main() {
   float e = simple_float();
   printf("after return : %.2f\n", e);

   return 0;
}

float simple_float() {
    float a = 5.63129;
    printf("before return : %.2f\n", a);
    return 5.63129;
}

But the output is displaying as such:

enter image description here

2 Answers

This will not even compile if you try gcc/clang. I'm surprised visual C allows this. Does it not have any stricter settings ?

By default, C assumes the return type of any function as ‘int’. So, declare the function prior, which is good practice anyway. Fyi, errors from a C99 compliant compiler:

foo.c:6:14: warning: implicit declaration of function 'simple_float' is invalid in
      C99 [-Wimplicit-function-declaration]
   float e = simple_float();
             ^
foo.c:12:7: error: conflicting types for 'simple_float'
float simple_float() {
      ^
foo.c:6:14: note: previous implicit declaration is here
   float e = simple_float();
             ^
1 warning and 1 error generated.

The Problem with your code is that you are not declaring the function before using it. In that case, the compiler assumes the return type int:

#include <stdio.h>

float foo(void);

int main(void) {
  printf("With known prototype : %.2f\n", foo());
  printf("Without known prototype : %.2f\n", bar());
  return 0;
}

float foo() {
  return 5.63129f;
}

float bar() {
  return 5.63129f;
}

will output 5.63 in the first line and 0.00 on my machine, compiled with vc. But that seems to depend on the machine.

Compiling this on gcc will result in an error.

Nearly every modern compiler warns about this when compiling and most of them throw an error because the type-check will find a conflict in the actual definition.

I just tried out different compilers, and indeed, there are some compilers that don't regard this as an error. E.g. vc and sdcc just warn the user, but they will generate an output that will result in undefined behaviour.

Related