Why doesn't this work int/long?

this one works but yr has to be a long. if int you get wrong answers.
char buf[11];
int dy = 16;
int mo = 6;
long yr = 21;
long xx = 0;
xx = dy;
xx += mo * 100;
xx += yr * 10000;
ltoa(xx, buf, 10);
Serial.println("date "); Serial.println(buf);

but this one gives wrong answers even tho 21 easily fits into int.
char buf[11];
int dy = 16;
int mo = 6;
int yr = 21;
long xx = 0;
xx = dy;
xx += mo * 100;
xx += yr * 10000;
ltoa(xx, buf, 10);
Serial.println("date "); Serial.println(buf);

yr is an int. So is 10,000. When you multiply them together you get integer overflow before trying to put the result in a long.

Do the calculations by hand. See how big the numbers get. Learn how large a number can be and fit into an int and a long variable.

a7

void setup()
{
   Serial.begin(115200);
   char buf[11];
   int dy = 16;
   int mo = 6;
   int yr = 21;
   long xx = 0;
   xx = dy;
   xx += mo * 100L;  // add L to force long calculation
   xx += yr * 10000L;  // add L
   ltoa(xx, buf, 10);
   Serial.println("date "); Serial.println(buf);
}

void loop()
{

}

The L in the calculations force the calculation to be done with long data type. See here.

1 Like

depends if it is an African or European int.

I had surmised the compiler would use the target for the answer as the workplace or define a long to multiply the two ints. But I guessed wrongly I guess.

one thing about the old mainframes, overflow would abend your program.

C doesn't care: "You want overflow? I got your stinkin' overflow right here!"

The compiler looks at the expression first and decides it's all ints, so ok, integer math. Oh look, he wants to put it in a long comes later, after the overflow.

You guessed right about guessing wrong. And I am not guessing.

Pro tip: guess work and computer programming do not mix well.

Documentation can be consulted for the "truth".

Or get empirical - a few minutes of hacking with various changes can reveal a lifetime of knowledge.

The more you know already, the more focussed and meaningful your experments.

a7

you have to guess. often the answer is not obvious.

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