stefdeve
stefdeve

Reputation: 31

Weird behavior of simple C code with float input and output values

I cannot explain this behavior: same function with same input parameters called from two different positions gives two different answers. But it should not!

Float result is 0 in some cases and I can't explain why.

This is a simple piece of code:

#include <stdio.h>

void main(int argc, char** argv)
{
  bar((1.0/16));  //prints input
  foo();          //calls bar((1.0/16));
}

void bar(float x){
  printf("%f\n",x);
}

void foo(){
  bar((1.0/16));
}

This is its output:

0.000000
0.062500

So the problem appears only when I use both a float type and a float value.

All this happens on a Windows 7 64 bit machine in Visual Studio 2010 SP1. Only settings I changed in project properties:

Configuration: Debug. Platform: win32.

Any idea?

Thanks a lot.

Upvotes: 2

Views: 259

Answers (2)

haccks
haccks

Reputation: 106012

You are calling the function bar and foo without their previous declarations. When the compiler encounters the first call of bar/foo, it doesn't know about how many parameters these functions would have, what types of parameters are or what kind of value they will return.

Instead of producing any error/warning, compiler assumes that foo returns an int value (note that the return type of a function is int by default. But in C99 and latter this has been dropped and you will get a compilation error.) and that's why you are getting 0.000000 for first call of foo.

You should put a prototype before main.

void bar(float x);
void foo(void);

Upvotes: 2

Some programmer dude
Some programmer dude

Reputation: 409176

It's ecause you don't have a prototype of bar before you call it the first time from main, so the compiler will try to guess what argument type the function have, and as you pass a double argument to it (1.0 / 16 is of type double) it will pass a double value to a function which actually takes a float argument. That mismatch in parameters leads to undefined behavior.

There are two ways to fix this:

  1. Declare the function (write a prototype) before calling the function.
  2. Change the argument type to double.

I recommend number 1 in the list.

It will not work to pass a float value to the function (e.g. 1.0f / 16) since since for implicitly declared functions like yours the arguments are promoted to the default type, which for floating point values is double. Also note that implicitly declared functions are expected to return an int.

Upvotes: 4

Related Questions