This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

CCS V6 - different results for same value assignment

I have possibly a stupid question regarding variable assingnment.
I noticed the following with CCS  Version: 6.1.1.00022 :

Code example:

unsigned long x,y;

x= 2*24*3600;   results x= 0xFFFF3a00 which I do not expect

y = 172800;      results y=0x2A300 which is correct.


Could it be that the compiler has a problem or am I wrong?

Thanks

  • You're probably using a target where int is 16 bits. In that case, each of those integer constants is a 16-bit int, and when you multiply 2*24*3600, you get a value larger than INT_MAX, which is undefined behavior due to signed integer overflow. Change just one of those constants to a long constant by putting L on the end and I'll bet you get the answer you expect.
  • I presume you use an MSP430 device.  On MSP430 int is 16-bits and long is 32-bits.  A similar thing happens on any device with same sizes of those types.

    Integer constants default to the type int.  The rules regarding what happens with types as expressions are evaluated are the same whether or not the operands are constants.  In this case, multiplying two int constants results in an int type.  When an int type is widened to a 32-bit type, sign extension is performed.  This is true regardless of the signness of the wider type. 

    The best way to fix this is to use the L suffix in the constant 3600.

    x = 2*24*3600L;

    That causes all the intermediate results to be of type long, and gives you the result you expect.

    Thanks and regards,

    -George

  • Hello,

    Thank you both for the quick answer.

    Yes, I'm using MSP430. Your proposal fixes my problem. I wasn't aware of that.
    I'll take care in the future.

    Thank you again.
    Regards

    Robert