Pages: [1]   Go Down
Author Topic: what's the different between int & byte, while i=0  (Read 480 times)
0 Members and 1 Guest are viewing this topic.
0
Offline Offline
Newbie
*
Karma: 0
Posts: 2
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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 :-/
Logged

London
Offline Offline
Faraday Member
**
Karma: 8
Posts: 6240
Have fun!
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

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

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 ?
« Last Edit: January 02, 2008, 04:02:43 am by i3dx » Logged

Forum Administrator
Cambridge, MA
Offline Offline
Faraday Member
*****
Karma: 9
Posts: 3538
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

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

Pages: [1]   Go Up
Jump to: