My sketch was taking up 99% of available program space (99% or 30720 bytes on a NANO), so I started to optimize more of the code.
I have a function outside the main loop that receives string commands from a BLE module.
This function processes these commands to do certain things in a large case statement. When making some small changes, all of a sudden, the code space dropped by over 4k bytes down to 83%.
I tracked it down to one single statement at the top of this function where I was declaring a simple counter variable:
void ProcessMsg(String msg) {
unsigned int cnt;
switch(cmd-0) {
....
case 'g':
cnt=0;
...
break;
....
}
}
What I changed was that I moved that int declaration to inside the one case block that used the 'cnt' counter to make it more readable. Inside the case statement, I did have a "cnt=0;" statement to initialize the variable, so I combined those two statements into this one statement inside the case block:
switch(cmd-0) {
case 'g':
unsigned int cnt=0;
...
break;
...
}
As soon as I did that, the code space droped by 4,466 bytes (83% of total space available). Literally, just by adding "= 0" frees up 4k of space.
If I leave the int declaration inside the case block and do not initialize it with a value, it does not reduce the code space (still @ 99%)
switch(cmd-0) {
case 'g':
unsigned int cnt;
cnt=0;
...
break;
...
}
And if I move that line back outside the case statement and initialize it with a value, the code space doesn't change either.
void ProcessMsg(String msg) {
unsigned int cnt=0;
....
}
The program code space is only reduced by 16% when this statement is both inside the case block and initialized.
Why?
(I don't want to post my entire sketch, it's very long).