An Interesting Warning in C and C++

by Codewiz51 January 08, 2009 18:47

While working on WinROTT, I have come across a couple of warnings that may actually be serious bugs. One warning is C4309: 'initializing' : truncation of constant value.

This appears to be innocuous. But maybe it's not.

The following statement generates a C4309 warning:

signed char tx = 0x80;

The value of tx is -128 after this declaration and initalization occurs.

Let's assume this is followed by:

// value of tp is 128
unsigned char tp = 0x80;
bool tc = tx == tp;

What's the value of tc? You might think it is true. But in reality, the comparison is -128 == 128 which is false.

This may be a contrived example. But consider when you are working in a normal c++ program, where the type may be hidden:

// header file (.h)
#define SF_BAT      0x80

// Forward only linked list
typedef struct  statestruct
{
    byte                rotate;
    short               shapenum;    // a shapenum of -1 means get from ob->temp1
    short               tictime;
    void                (*think) (void *);
    signed char      condition;     // GH originally signed char
                                             // Caused 0x80 to be assigned as -128
    struct statestruct    *next;    // Link to next struct
} statetype;

// implementation file (.cpp)
// C4309 warning occurs here
statetype s_batblast4 = {FALSE,BATBLAST4,3,T_Projectile,SF_BAT,&s_batblast1};

// Here's where the execution problem occurs
// This comparison will always return false
if (s_batblast4->condition == SF_BAT)
{
    // Do something here
}

The moral is, don't ignore warnings. They may not be harmless. In this case, changing condition to unsigned char is the correct fix.

Comments

1/9/2009 4:53:43 PM #

keep up the good work ( what I was to looo lazy to do)
Birger

birger Denmark

1/9/2009 6:38:09 PM #

You weren't too lazy. You did the heavy lifting and got WinROTT working. I'm just polishing the finish.

gharris United States

Comments are closed

Powered by BlogEngine.NET 1.6.0.0
Theme by Mads Kristensen | Modified by Mooglegiant

Disclaimer

This blog represents my personal hobby, observations and views. It does not represent the views of my employer, clients, especially my wife, children, in-laws, clergy, the dog, the cats or my daughter's horse. In fact, I am not even sure it represents my views when I take the time to reread postings.

© Copyright 2008-2011