All courses

Arduino C++ · Lesson 29 of 40

Choose types and protect array boundaries

Reliable Embedded C++

Small boards make type choices visible

On an Uno R3, int is normally 16 bits, while long is 32 bits. Other Arduino cores can use different widths. Use uint8_t, uint16_t, and uint32_t when storage width matters; use unsigned long for millis() timestamps to match the API. An ADC result can fit in int, but a sum of 100 full-scale ADC samples cannot fit in a signed 16-bit int.

Widen operands before arithmetic. Assigning an already-overflowed int expression to a long does not recover the original value. Use 1000UL * seconds for millisecond conversion. Unsigned wrap is defined; signed overflow is not a reliable wrapping technique.

Integer division truncates: 3 / 2 is 1. Write 3.0f / 2.0f when you need 1.5. A printed decimal does not mean the source measurement is accurate to that many places.

Keep length beside the array

Arduino C++
const byte ledPins[] = {3, 5, 6};
const size_t ledCount = sizeof(ledPins) / sizeof(ledPins[0]);

void setup() {
  for (size_t i = 0; i < ledCount; ++i) {
    pinMode(ledPins[i], OUTPUT);
  }
}

void loop() {
  for (size_t i = 0; i < ledCount; ++i) {
    digitalWrite(ledPins[i], HIGH);
  }
}

If you build this optional circuit, each D3/D5/D6 output needs its own LED and series resistor to GND. A three-element array has indices 0, 1, and 2. Using i <= ledCount reads past its end. sizeof(array) works where the compiler sees the actual array, not inside a function receiving only a pointer. Pass an explicit length to such a function.

Practice: Predict the result of 1000 * 60 on a 16-bit-int target, then compare it with 1000UL * 60. Enable compiler warnings in IDE preferences and investigate each conversion warning. Test array loops at length zero, one, and their maximum supported length.

Official references for further study

A useful reminder

Clean Code: Use descriptive constants instead of magic numbers

Instead of calling digitalWrite(13, HIGH) directly in your code, define descriptive constants like const int LED_PIN = 13; at the top of your file. This makes your code self-documenting and extremely easy to update if you change your wiring.