Arduino Mega

I would like to have an array containing analog pin labels something like...

int analog_pins[] = {A0, A1, A2, A3};
int num_analog_pins = sizeof(analog_pins) / sizeof(analog_pins[0]);

Is this possible? It has compiled without any warnings or errors but I'm dont have my board with me (yes beginners mistake) so cant really check if it works.


As you can see in Arduino.h, the analogRead() has uint8_t as parameter. You can define them as byte or uint8_t and you don't have to use the sizeof().

The type of A0 is defined in the file pins_arduino.h:

#define PIN_A0 (14)
static const uint8_t A0 = PIN_A0;

Nevertheless, what you have with integers is 100% okay as well.

When you don't have a Arduino board available, you can use the simulation of an Arduino Uno at Tinkercad.

As @DataFiddler writes below this answer, using a 'const' keyword is preferred:

const uint8_t analog_pins[] = {A0, A1, A2, A3};
  • 1
    const uint8_t analog_pins[] might even be better, eventually allowing for a lot of compiler optimization Mar 16 '19 at 15:57

Your calculation will be correct for num_analog_pins, however it's convention to use the type of the array like so

int num_analog_pins = sizeof(analog_pins) / sizeof(int);

As @Jot noted, you'd save much space by declaring your array using uint8_t like so

uint8_t analog_pins[] = {A0, A1, A2, A3};
uint8_t num_analog_pins = sizeof(analog_pins) / sizeof(uint8_t);
  • 1
    sizeof(uint8_t) :-) very formal
    – Juraj
    Mar 16 '19 at 15:27
  • @Juraj haha indeed! I've always written such code for portability and clarity. Mar 16 '19 at 15:30
  • @RamblinRose You should write uint8_t num_analog_pins = sizeof(analog_pins) / sizeof(analog_pins[0]);
    – SBF
    Mar 16 '19 at 15:42
  • @MarkSmith I'm confused by your comment - sizeof returns the number of bytes allocated for an array, sizeof(array) / sizeof(array_type) = number of array elements. Mar 17 '19 at 13:16
  • Apologies, I hadn't seen the denominator there. Comment deleted.
    – Mark Smith
    Mar 17 '19 at 13:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.