When an Int Runs Out
Part of the First Circuits section of Coddy's Arduino journey. Lesson 12 of 22.
A variable is stored in a fixed number of bits, tiny on/off switches in the board's memory. On the Uno, an int has 16 bits, so it can only hold numbers from -32,768 to 32,767.
Go past the top and it does not grow: it wraps round to the bottom. 32,767 plus 1 becomes -32,768. This is called an overflow, and the sketch gives no warning.
For bigger numbers, use a type with more bits:
long big = 100000; // -2,147,483,648 to 2,147,483,647
unsigned long huge = 3000000000; // 0 to 4,294,967,295long has 32 bits. unsigned long has 32 bits but no negative numbers, so it goes twice as high: good for counts and times.
A long takes twice the memory of an int, and the Uno has only 2048 bytes for variables, so use int when the numbers stay small.
Challenge
MediumThe starter adds 1000 to count twenty times a second. Press Run and watch it turn negative after 32,000.
- change the type of
countso it can count past 100,000
Then Check.
Try it yourself
int count = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
count = count + 1000;
Serial.println(count);
delay(50);
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in First Circuits
2Talking to Your Computer
Hello, Serial MonitorPrint Versus PrintlnPrinting NumbersYour First VariableCounting UpWhen an Int Runs OutPractice on your own: Arduino playground