Strange output on Variables

My Serial.Monitor is telling me that "HeaterLength" 4294961760. But it Should be 60000. I thought it had something to do with the variable type. Originaly it was a integer. Therefore i got a negativ Value of -5xxx. So i switched to unsigned long. Now i have this strang number.

volatile byte newLength = 1;      //Starting TimerValue

unsigned long HeaterLength = newLength * 60 * 1000; 

I hope this code is enough. If not i will post the Rest.

THX

this part of the math is conducted using int (2 bytes on a UNO, signed maths so max is 32767)

so you overflow

try

unsigned long HeaterLength = newLength * 60ul * 1000ul; 

to force the math as unsigned long

1 Like

thank u. it works. but i dont understand :smiley:

when you do 1 x 60 x 1000 you genuinely expect the result to be 60000 but.... C++ does not see it that way

when you use numeric values, the compiler needs to decide what type to use to represent the value. It always takes the smallest type that can represent the data, starting with int

As 1, 60 and 1000 fit on an int that's the type the compiler will use for the math.

An int type is stored on 2 bytes in your arduino. The value you can represent on 2 bytes (signed) are between -32767 and + 32767.

so 1 x 60 - that's fine, it's within range so you get 60 and it's still an int. But then you have 60 x 1000 and 60,000 does not fit as it's more than 32767 and so the compiler will only keep the bits that fits on 2 bytes as an int and it will become a negative value -5536 and when you extend this negative value to get an unsigned long that's where you get 4294961760

by using the ul suffix for the numbers, you tell the compiler what type to use for the maths - here unsigned long (32 bits) which can represent data up to 4 294 967 295

so 1 x 60ul is conducted as an unsigned long (32 bits) and then you multiply also by a 32 bit value 1000ul and 60,000 does fit (plenty of room ) below 4294967295 and so you get the right result

1 Like

so far so good. i thought this is what i explained in the beginning. So i changed the Variable Type to an unsigned long to fix this. Why didnt this work? why do i have to add "ul"?

the destination variable does not influence the way the math is done before the assignment.

1 x 60 x 1000 is calculated using C++ rules for maths regardless of what the result is used for.

Only then whatever result you got is promoted (using C++ rules for promotion) into the destination variable's type.

so you use ul to force the math on the right side of the assignment to be conducted using unsigned long, not the default int.

Optimization ,saving memory unless defined different by adding "ul".

???

not sure what you mean by Optimization ,saving memory

this happens regardless of your Optimization flags. that's the C++ standard

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.