July 07, 2004

No warning when passing a bool constant as a float param

Sorry to the non-programmers that read this (Hi mom! :)), I really should move this over the programming section, but I’m at work and don’t have time.

So consider the following bit of code (I hope it formats ok…)

void func (float f)
{
	float _f=f;
}
 
int main (int argc,char *argv[])
{
	func (true); // <--
}

You would expect a warning when func is called. But with visual c++ 7.0 and 7.1 there is no warning. I spent a few hours tracking down a bug because I didn’t get a warning, so I wanted to point it out to others.

Even with /Wall there is no warning:

c:\temp>cl /Wall test.cpp
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 13.10.3077 for 80x86
Copyright (C) Microsoft Corporation 1984-2002. All rights reserved.

test.cpp
test.cpp(3) : warning C4189: '_f' : local variable is initialized but not refere
nced
test.cpp(6) : warning C4100: 'argv' : unreferenced formal parameter
test.cpp(6) : warning C4100: 'argc' : unreferenced formal parameter

I haven’t tried this in gcc, but using sourceforge’s pastebin I tried it with Comeau and got no warning.

*EDIT* I’m sure it’s not an optimization, here is another version of the, code, that actually does ‘something’.

#include 

char func (float f)
{
return (char)f;
}

int main (int argc,char *argv[])
{
printf ("Testing %c",func (0xFFFFFFFF)); // <--
printf ("Testing %c",func (true)); // <--
}

The line that takes the unsigned int constant gives the warning “warning C4305: 'argument' : truncation from 'unsigned int' to 'float’” but the line that takes the bool has no warnings.

I think it’s a “feature” of the language, allow you to do things like lightColor = lightColor * IsLightingOn(); where IsLightingOn() returns a bool, which gets converted to either 0 or 1. It’s an implicit conversion that just feels wrong to me.

Posted by Gareth at July 7, 2004 04:38 AM
Comments

Did you get to the bottom of why this is valid? I'm guessing it's not something silly like stripping out uncalled code?

Posted by: Mark at July 9, 2004 05:01 PM
Post a comment









Remember personal info?