Does array make the program smaller?

Hi everyone,
is there a difference in program size between these two declarations:

1- int n1,n2,n3,n4,n5,n6,n7,n8,n9,n10;
2- int n[10];

I know array is much better, but we may have different variables is it better if we put them all in one array or same ?

Thank you


Not by the declarations. Your code can become smaller if you can use code loops (for...) over the array.

what does this mean?

Thank you, I was going to ask if loops make program smaller

I mean that the elements of an array usually have common property for many items (like 5 analog readings),
but if we have vars for uncommon things like "counter" , "analog read" , "pwm output" .. etc.
should we put them in one array ?

Its your choice makes no difference to the size of the variables. However in C all the variables in an array must be of the same type.

You would usually group in an array things that are related for example if you have LEDs connected to pins, you could do

const byte ledPins[] = {2,3,4,5,6,7}; // pins driving my leds
const byte ledCount = sizeof ledPins / sizeof ledPins[0] ; // number of pins calculated by the compiler

which would be better than

const byte ledPin1 = 2;
const byte ledPin2 = 3;
const byte ledPin3 = 4;
const byte ledPin4 = 5;
const byte ledPin5 = 6;
const byte ledPin6 = 7;

const byte ledCount = 6;

as you don't need to modify the count manually if you add a led later on or modify the code as you can use a for loop to efficiently "talk" to all LEDs

for (byte i = 0; i < ledCount; i++) pinMode(ledPins[i] , OUTPUT);

or the fancier Range-based for loop

for (auto && aPin : ledPins) pinMode(aPin, OUTPUT);

but if you have a pin that does not "conceptually" fit in the same group, say you have also a button or a sensor connected to an analogPin, then you would declare a special constant for those.

const byte buttonPin = 8;
const byte sensorPin = A0;

and not add those into the array.

➜ keep things organised in a way that makes sense and that will help read the code. (and that would take the same amount of SRAM memory)

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.