How to make default case in C

In the microcontroller program, I have several instructions that I would like to follow for each case on the switch, except for the default value. However, I do not want to write a function call or use a macro for each case.

Since this is for a microcontroller operating at a speed of 3-7 MHz, speed and code space are important. For instance:

switch(letter) { case a: ShowApple(); printf("You entered an english letter."); break; case b: ShowBananna(); printf("You entered an english letter."); break; ... case z: ShowZebra(); printf("You entered an english letter."); break; default: printf("You did not enter an english letter. Silly human!"); break; } 
+4
source share
4 answers
 int was_default_picked; was_default_picked = 0; switch (letter) { // ... default: was_default_picked = 1; } if (!was_default_picked) { // Your logic goes here } 
+5
source

I'm going to go to hell for this ...

 switch (foo) { default: /* code for default case */ break; if (0) { case 'a': /* ... */ } if (0) { case 'b': /* ... */ } if (0) { case 'c': /* ... */ } /* common code for non-default cases */ } 
+5
source

Why don't you use an array of function pointers indexed by letter instead of switch ? It will be both more space and speed. And, IMO, are more readable.

 static void (*fn_table['z' - 'a' + 1])(void) = { &ShowApple, &ShowBananna, ..., &ShowZebra, }; if (letter < 'a' || 'z' < letter) { printf("You did not enter an english letter. Silly human!"); } else { (*fn_table[letter - 'a'])(); printf("You entered an english letter."); } 
+3
source

If this is truly the last statement in each case, you can simply execute it after use with the if statement:

 int wasEnglish = 1; switch(letter) { case a: ShowApple(); break; case b: ShowBananna(); break; ... case z: ShowZebra(); break; default: wasEnglish = 0; break; } if (wasEnglish) { printf("You entered an english letter."); } else { printf("You did not enter an english letter. Silly human!"); } 
+2
source

Source: https://habr.com/ru/post/1392092/


All Articles