7.2: Nesting
- Page ID
- 35830
If a multiple condition won’t cut it, you can nest if/else tests. Nesting conditionals is easy:
if( test condition(s).. ) { if( other tests.. ) { } else { } } else { if( still other tests.. ) { } else { } }
You can go many levels deep if you desire. Note that C, unlike Python, doesn’t require the indenting shown, but it is expected formatting. For selection of a single value out of a list, you can use the switch/case construct. The template looks like:
switch( test_variable ) { case value_1: //...do stuff... break; case value_2: //...do other stuff... break; default: //...do stuff for a value not in the list... break; }
The default
section is optional. Also, it does not have to be the final item in the list. If a break
is left out, the code will simply fall through to the next case, otherwise code execution jumps to the closing brace. Also, cases can be stacked together. The action statements for each case may include any legal statements including assignments, function calls, if/else
, other switch/case
, and so on. Note that you cannot check for ranges, nor can the cases be expressions. The cases must be discrete values. The following example shows all of these. The action statements are replaced with simple comments.
switch( x ) { case 1: /* This code performed only if x is 1, then jump to closing brace */ break; case 2: /* This code performed only if x is 2, then jump to closing brace */ break; case 3: /* This code performed only if x is 3, but continue to next case (no break statement) */ case 4: case 5: /* This code performed only if x is 3, 4, or 5, */ break; default: /* this code performed only if x is not any of 1,2,3,4, or 5, then jump to closing brace (redundant here) */ break; }
Sometimes it is very handy to replace the numeric constants with #define
values. For example, you might be choosing from a menu of different circuits. You would create some #define
values for each at the start of the file (or in a header file) as so:
#define VOLTAGE_DIVIDER 1 #define EMITTER_FEEDBACK 2 #define COLLECTOR_FEEDBACK 3 /* etc... */
You would then write a much more legible switch/case like so:
switch( bias_choice ) { case VOLTAGE_DIVIDER: /* do volt div stuff */ break; case EMITTER_FEEDBACK: /* do emit fdbk stuff */ break; /* and so on... */ }