Archived

This topic is now archived and is closed to further replies.

Compiler Warning

This topic is 5673 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, I''m using VC++ 6 as most of you do, I imagine. Anyways, what''s with the following performance warning? Compiler Warning (level 3) C4800 forcing value to bool ''true'' or ''false'' (performance warning) MSDN has giberish bout the reason why it''s bad. Anybody have a clue?? Thanks.

Share this post


Link to post
Share on other sites

int i = 6;
if( i ) // <- right here
do_something();

The variable i is being evaluted within a context expecting a boolean value, thus implicitly converting i from an integer to a boolean (any non-zero value converts to true; zero is false). This is okay with integers and other numeric types, but the compiler issues a warning in case of situations like this:

char * c = "What''s my name?";
if( c )
do_something_else();

Here the compiler can''t tell what you''re trying to do, because even though the value is non-zero (value at c would be ''W'' - look it up in your ASCII chart), it''s not boolean and might actually be a logic error on your part.

Generally, warnings are to call your attention to possible mistakes that the compiler can''t detect on its own. Look at them, evaluate them, and take proper action. In the first case, you can ignore it. In the second case, you shouldn''t.

Share this post


Link to post
Share on other sites
Not that it matters much at all, but Oluseyi''s example:


  
char * c = "What''s my name?";

if( c )
do_something_else();


This will always evaluate to true, since the char string pointed to by c will be at a non-zero memory address.

[Sorry for sounding like a nit-picking ass, but I''m bored at work ''n need something to do.]

Share this post


Link to post
Share on other sites
Thanks for the replies.
I realize that the compiler treats booleans as zero or non-zero. Like the ever dangerous:

if( var = x )
always true;

as opposed to: if( var == x )

My question though is about the potentional "performance"-hit the compiler is suggesting. Does narrow-casting from int to bool cause a hit whatsoever? I don''t see at all why it would.

Thanks.

Share this post


Link to post
Share on other sites