Go Down

### Topic: what's the different between int & byte, while i=0 (Read 2206 times)previous topic - next topic

#### i3dx

##### Jan 02, 2008, 09:19 am
int pin[] = {
2,3,4,5,6,7,8,9,10,11};
void setup(){
for(int i = 0; i <= 9; i++){
pinMode( pin,OUTPUT);
}
}
void rt(){
for(byte i = 9; i >= 0; i--){
digitalWrite(pin,HIGH);
delay(50);
digitalWrite(pin,LOW);
}
}
void loop(){
rt();
}

show noise :-/

#### mem

#1
##### Jan 02, 2008, 09:54 am
The difference is that the compiler will use a single 8 bit variable for the counter in the machine language it produces rather then a 16 bit variable. The object code produced is 10 bytes smaller then it would be if int was used in that loop rt instead of byte.

You can use byte when you are absolutely sure that your variables will never exceed 255 (or +- 127 if signed)

But int is safer from overflow bugs and the slight loss in program size and efficiency usually doesn't matter,

#### i3dx

#2
##### Jan 02, 2008, 10:01 amLast Edit: Jan 02, 2008, 10:02 am by i3dx Reason: 1
But, while byte i = 0 the program don't stop loop in the for(byte i = 9; i >= 0; i--){}
continue to do i-- 10 times, so you'll get 255 254 253 252 251 250 249 248 247 246
maybe  ONE bug ?

#### mellis

#3
##### Jan 02, 2008, 03:14 pm
A byte only goes from 0 to 255.  So i >= 0 is always true (if i is a byte).  When you subtract 1 from a byte with a value of 0, it wraps around and you get 255.  You could change the loop to for (byte i = 10; i > 0; i--) and then use (i - 1) inside the loop.

Go Up