Besides being an ideal candidate for the obfusicated C contest, the
following code produces some odd results depending on the optimization
settings for the compiler.  Essentially the code calculates the required
size for a packed record.  It sums the lengths of the fields in my structure
and adds the null byte if it is needed.

        //add the string lengths + the null byte
        //I know using the "?:" operator is bad programming b/c it hurts
readability
        //but I wanted to keep the code compact
    RecordSize=(len=StrLen(Data.Field1))+((len>0)?1:0);
    RecordSize+=((len=StrLen(Data.Field2))+((len>0)?1:0));
    RecordSize+=((len=StrLen(Data.Field3))+((len>0)?1:0));
    RecordSize+=((len=StrLen(Data.Field4))+((len>0)?1:0));
    RecordSize+=((len=StrLen(Data.Field5))+((len>0)?1:0));
    RecordSize+=((len=StrLen(Data.Field6))+((len>0)?1:0));
    RecordSize+=((len=StrLen(Data.Field7))+((len>0)?1:0));
    RecordSize+=((len=StrLen(Data.Field8))+((len>0)?1:0));
    RecordSize+=((len=StrLen(Data.Field9))+((len>0)?1:0));
    //...//
    RecordSize+=(sizeof(PackedHistoricStruct)-1);//room for a record header
    if(RecordSize%2==1)//keep the record on word boundries
        RecordSize++;
    HistoryP=(PackedHistoricStruct*)MemPtrNew(RecordSize);
//this code is for testing the resulting recordsize
StrPrintF(Str2,"%ld",RecordSize);
WinDrawChars(Str2,StrLen(Str2),30,20);

I'm using CodeWarrior version 6.  When optimizations are set to level 2
(Global Register Allocation, Peephole, Dead Code Elimination, Common
Subexpression Elimination, Copy Propogation) with Smaller Code Size
selected, gremlins run on my app merrily for days on end without finding a
thing.  However, bumping optimizations up a notch (adds Loop
Transformations, Strength Reduction, and Loop-Invariant Code Motion) causes
a memory data structure write.

After adding the WinDrawChars line I noticed that RecordSize isn't getting
the correct value when optimization is set to level 3.  My theory is that
the compiler is having trouble with setting the len variable and comparing
it in the same line of code.

The bug was easily fixed by seperating the set of len from its comparison
every where it was used.  However I would like to know what exactly I did
wrong so that I can avoid inadvertantly doing it again.

Is this code unacceptable?
RecordSize=(len=StrLen(Data.Field1))+((len>0)?1:0);

Or did I find a compiler bug?

Thanks,
Mike


-- 
For information on using the Palm Developer Forums, or to unsubscribe, please see 
http://www.palmos.com/dev/support/forums/

Reply via email to