Pages: [1]   Go Down
Author Topic: long initialization bug  (Read 480 times)
0 Members and 1 Guest are viewing this topic.
0
Offline Offline
Newbie
*
Karma: 0
Posts: 20
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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....
Logged

0
Offline Offline
Newbie
*
Karma: 0
Posts: 20
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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.
Logged

0
Offline Offline
Faraday Member
**
Karma: 8
Posts: 2526
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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
Logged

0
Offline Offline
Newbie
*
Karma: 0
Posts: 20
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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?
Logged

0
Offline Offline
Faraday Member
**
Karma: 8
Posts: 2526
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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
Logged

Pages: [1]   Go Up
Jump to: