Since state values in a state machine can be defined using an enum, it seems like a good approach to use a switch statement and let the compiler generate a jump table.
However, it seems dependent on the compiler's optimization option. So I checked both the UNO R4 and the ESP32, and it appears that both use the -Os optimization flag (which prioritizes minimizing code size based on -O2).
That said, I cannot be certain without examining the assembly output. I am not sure how to view the assembly code within the Arduino environment, so if anyone happens to know, I would appreciate it if you could let me know.
What you need to do is compare it to not using a switch statement.
Depending on what you are depending on, the speed of the dispatch may be immaterial. Not never to be worried about, but down there most times with things like the "slow" speed of digitalWrite().
I agree the switch statement is cleaner and easier from the hman point of view, both writing reading them.
The discussion @embeddedkiddie is worth some attention. I don't think I would remember and bother making the process faster by being nice about how I wrote it or the values I used for the cases.
It may not be available in the IDE; but it is in the Command Palette on Wokwi. If you forget how to invoke that, it's in the right-click menu in the Editor, which also says you get it by pressing F1. Then in the Palette, search for View Compiled Assembly Code Listing
It can be either, depending on the values and the compiler settings: dense, sequential values often become a jump table, while sparse values are more likely to be checked in turn or through a more efficient search. In practice, that dispatch cost is usually tiny compared with what each state actually does, so I would keep the switch for readability unless timing measurements show it matters. If a state transition is truly time-critical, measuring that section and keeping the work inside each case short will tell you more than guessing about the dispatch method.
switch/case statement is an 'goto' statement under the hood.
This is why , for example, this is a valid C code:
#include <Arduino.h>
void setup() {
Serial.begin(115200);
}
void loop() {
int i = 1;
switch (i)
if (0) case 1 ... 10: puts("i = 1 ... 10"); // if(0) или все же нет? :)
else if (0) case 0: puts("i = 0");
else if (0) case 11: puts("i = 11");
else if (0) default: puts("i = something else");
delay(1000);
}
At school we had lessons about parsers and compilers. IIRC there were different strategies for switch case. I recall
Calculate offset in a jump table
If then else ladder
If then else tree
Other?
Strategy chosen depended on datatype and the number of options strongly related to search strategies.
The calculated jump is fast but could be memory hungry, In essence it is a hash strategy
The if ladder is fast if there are only a few cases. Or if one knows probability of the cases, it might be made slightly faster by reorganizing the order. It is in essence a linear search through the cases.
The if tree is a (binary) search through the cases and is only faster for a larger number of cases.
A mix of tree search for the first steps and linear search for the last steps can be optimal.
If the switch supports ranges, it can be seen as many adjacent cases that can be handled with one or two if tests.
There might be more strategies but most often the switch is not the (performance) bottleneck in a program as said before. Human readability for maintainability is more important imho.
Outside C++ there are other techniques such as a jump table on the string length before comparing the strings, as Go does for string switches, or a jump table on some bits of the type hash for type switches, instead of a binary search on the full hash.
For C++, where a switch only accepts integral or enumeration types, you have bit tests, where a bitmask encodes which inputs go to a given target and a single bit test instruction decides the branch, result lookup tables when the case bodies only yield constants, pure arithmetic when the mapping follows a formula, and as you noted hybrid clustering, where the cases are split into groups each handled by the most suitable technique, with a balanced binary search choosing between the groups.
PS:
If you wonder what a result lookup table is, it is when a switch is used only to map an input to a constant, so the compiler stores those constants in an array and indexes it instead of generating code for each case.
For example, if you have
const char *errorMessage(int errorID) {
switch (errorID) {
case 0: return "OK";
case 1: return "File not found";
case 2: return "Permission denied";
case 3: return "Out of memory";
default: return "Unknown error";
}
}
the compiler might turn it into something looking like this:
static const char *const table[] = {"OK", "File not found", "Permission denied", "Out of memory"};
const char *errorMessage(int errorID) {
if ((unsigned)errorID > 3) return "Unknown error";
return table[errorID];
}
The basic idea of a switch-case is in fact a speed and code length optimization.
Comparing 'V' with y1, y2, y3 & y4, 'X' is loaded into one side of the compare register and y1, y2, y3 & y4 are loaded when required, whereas with a series of 'if' statements, x has to be re-loaded into the compare register every time.
Also the condition only checks for a match (no bigger or smaller) but i am not sure that matters much these days.
Therefore to compare in that matter just requires less instructions. On an MCU with some memory like an UNO, the saving on progmem is usually not much and also speed wise the difference is marginal unless that particular bit of code is executed very often repeatedly. (we are talking just a single load instruction and in most cases just an 8 bit value)
On an Attiny13 on the other hand with only 1 KB of progmem, this can make quite a lot of difference and the fall-thru may be an added bonus. (effectively 'OR'-ing conditions)
That it looks more neat in the source code is cool, but that was not the goal. It really is (or should be) smaller and faster than a series of 'if' statements, and the question for me is whether a compiler would optimize a series of 'if' statements into a switch-case if that is possible, to save time and space, but i actually don't think it ever does.
I think even BASIC has an equivalent of this, i.e. the "computed GOTO".
Of course basic is an interpreted language so that it calculated dynamically but in C/C++ it would logically be done at compile time.
To see the assembly locally: in IDE 2.x enable File > Preferences > "Show verbose output during: compilation", then compile. The log shows the build folder and the toolchain path. Use Sketch > Export Compiled Binary (or the build folder from the log) to get the .elf file, then run the toolchain's objdump on it, for example avr-objdump -d -S sketch.ino.elf > out.txt. For the UNO R4 the tool is arm-none-eabi-objdump, and for ESP32 it is xtensa-esp32-elf-objdump. The -S option interleaves your source lines with the instructions, which makes it easy to find the switch and see whether it became a jump table or a chain of compares. The .map file in the same folder also helps.
@colorfulcms, thank you for the tips.
I’ve bookmarked your post.
By the way, I wrote a simple sketch like a traffic light, where one of the blue, yellow, and red LEDs light up in sequence each time the switch is pressed.
And looked into the assembly code using Wokwi @kenb4 was introduced.
The sketch handles up to four states (including the initial state), the resulting assembly code is assembled as a series of sequential comparisons followed by jumps.
In this case, as @J-M-L pointed out, using a lookup table would have been a better approach; that would be more concise source code.
In any case, as everyone has noted, readability and maintainability should be the top priorities.
I still don't know which way any source I type might compile so maybe just maybe when the data lines up like translate ASCII to IBM a better way might be to slice input up by sets as opposed to a big fat LUT.... unless there's flash to spare and these are the kinds of things that make me want to keep code as flexible as possible in the pursuit of speed when needed and size to allow room for moar.
The standard reserves every identifier that contains a double underscore in any position…
The restriction is not enforced as a hard compile error. Most compilers will accept such a name, but the program is formally ill-formed, I think in practice it’s undefined behavior.
The real risk is a collision with a macro or a compiler or library internal that happens to use the same name, which can produce confusing errors or silent breakage on a different compiler or version.