Actions

EmSys

CCoding Style - Use else-ifs for multi-way decisions4

From EdWiki

Revision as of 06:51, 7 March 2012 by Jshankar (Talk | contribs) (1 revision)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Use else-ifs for multi-way decisions ...

Attempts to reuse pieces of code often lead to tightly knotted programs:

switch( c ) {
    case-: sign = -1;
    case+: c = getchar();
    case ‘.’: break;
    default: if( !isdigit(c) )
	return 0;
}

This uses a tricky sequence of fall-troughs in the switch statement to avoid duplicating one line of code.

A more traditional layout and structure is easier to read:

switch( c ) {
    case-: sign = -1;
    case+:
        c = getchar();
        break;		    
    case ‘.’:
         break;
    default:
        if( !isdigit(c) )
	return 0;
        break;
}