Reputation: 31
Consider the following loop in C:
int i;
for (i = 1; i > 0; i++);
After i
reaches INT_MAX
, it will turn INT_MIN
at increment. Then i > 0
evaluates
false, and the for loop will terminate.
However, the same for loop will not terminate in Arduino, since i > 0
compares false
even if i
is -32768
.
Why is that?
PS. I'm using a Mega 2560 with Arduino version 1.0.5.
PPS. int is indeed 16 bit on Mega 2560
PPPS. The complete sketch below:
void setup () {
int i;
Serial.begin(9600);
for (i = 1; i > 0; i++);
}
void loop () {
Serial.println(100);
}
And I won't see any thing in the Serial Monitor
Upvotes: 0
Views: 137
Reputation: 31
Disassembling the setup function gives:
0000014a <setup>:
14a: 80 e3 ldi r24, 0x30 ; 48
14c: 94 e0 ldi r25, 0x04 ; 4
14e: 40 e8 ldi r20, 0x80 ; 128
150: 55 e2 ldi r21, 0x25 ; 37
152: 60 e0 ldi r22, 0x00 ; 0
154: 70 e0 ldi r23, 0x00 ; 0
156: 42 d2 rcall .+1156 ; 0x5dc <_ZN14HardwareSerial5beginEm>
158: ff cf rjmp .-2 ; 0x158 <setup+0xe>
so now it's clear: avr-gcc thinks the i > 0
in for(i = 1; i > 0; i++)
will never evaluates false and optimised the exit condition away.
Upvotes: 1
Reputation: 203
when int is defined, by default, its size is assumed to be of 16 bit by compiler.
But when you increment it beyond 32767 i.e.
int i=32767;
i++;
The size of 'i' is automatically increased to 32 bit. This is because the size is not specified in the declaration.
This causes your program not to stop at 32767.
Hence if you want to stop the for loop at 32767,
you have to specifically declare it as
short int i;
If you want to verify this, you can try following
short int x;
for(x=1; x>0; x++)
{
mySerial.println(x);
}
AND
int x;
for(x=1; x>0; x++)
{
mySerial.println(x);
}
Upvotes: 0
Reputation: 1797
Most likely, 'int' is also 32-bit on Arduino. It takes time to complete 2^31 iterations. You may change 'int' to 'short' and it should terminate as expected.
Upvotes: 0