Go Down

Topic: long initialization bug (Read 541 times) previous topic - next topic

du

Here's the sketch:

long num1 = 10 * 60 * 60;
long num2 = 36000;

void setup() {
  Serial.begin(9600);
}

void loop() {
  Serial.println(num1,DEC);
  Serial.println(num2,DEC);
  delay(1000);
}

The output from my NG (compiled with 0007) is:

-29536
36000

num2 is obviously right, num1 isn't.  The corresponding case for ints doesn't seem to have the same problem.  sizeof() shows they are both 4 bytes, so it shouldn't be overflowing.  However, if I do 10 * 160 * 20 (== 32000) it works fine, so I'm deducing the existence of an intermediate int somewhere in the compiler....

du

The simplest possible example above was posted after a couple hours of tearing my hair out.  Later I realized that even assigning 10 * 60 * 60 to num1 at runtime also had the problem.  So it may not be a compiler issue, but it's still whack.

kg4wsv

long contstants need an L at the end, e.g.  lnum = 1000000L;

In the case of the expression, typecast it, e.g. lnum2 = (long int) (10 * 60 * 60);

-j

du

I guess my C is rustier than I thought.  Still, it's a little odd that I got away with 36000 with no 'L' but I didn't get away with 10 * 60 * 60.  Also, gcc-avr (if that's the culprit) must be less forgiving than regular gcc, since I tried this in a regular program and it worked fine.  Are warnings suppressed by the Arduino IDE?

kg4wsv

Quote
Still, it's a little odd that I got away with 36000 with no 'L' but I didn't get away with 10 * 60 * 60.

Well, 36000 is > 32767 which is the largets int you can have, so gcc probably just assumed it was a long since it wouldn't fit in an int (this is just a guess on my part).

Quote
I tried this in a regular program and it worked fine.

The size of an int vs. a long int may be different on a different architecture.  Your computer most likely has ints and long ints the same size (32 bits), whereas the AVR has 16 bit ints and 32 bit long ints.

-j

Go Up