Sometimes you just have to step that extra mile and do something completely dodgy.
The termios way for setting baudrates uses macros to represent the bitrate. When you’re accepting a baudrate from the user, what’s the most sensible way to do it in C?
- Get the macro value directly from the user.
- Get the baudrate as a string, and then string compare to determine which baudrate you want, and set the flags appropriately.
- Get the baudrate as an integer, and then integer compare to determine which baudrate you want, and set the flags appropriately.
People answering 1 or 2 can hand in their C licenses.
So you’re doing integer comparisons, right? Hey, we can use a switch/case statement for that, right?
So shortly we get:
switch (baudrate) {
case 50:
baudflag = B50;
break;
case 75:
baudflag = B75;
break;
… etc …
Surely there must be a better way?
Thanks to the C preprocessor, we have a slightly better option…
#define SPEEDMAP(x) case x: baudflag = B ## x; break;
switch (baudrate) {
SPEEDMAP(50);
SPEEDMAP(75);
SPEEDMAP(110);
…etc…
I wouldn’t get too carried away with solving stuff this way though…