syque.com

The Psychology of Quality and More

| Menu | Books | Share | Search | Settings |

C Style: Standards and Guidelines (contents)

CHAPTER 6 : Layout

PART 3 : LAYOUT

CHAPTER 6 : Code Layout
6.1 Basic principles of code layout
6.2 Use of Spaces
6.3 Use of blank lines
6.4 Use vertical alignment
6.5 Indentation level
6.6 Line wrapping
6.7 Braces
6.8 Use of parentheses
6.9 Nested single statement
6.10 Empty statements
6.11 'else..if'
6.12 'switch' statements
6.13 'do..while'
6.14 Labels
6.15 Data declarations
6.16 Function declaration
6.17 Preprocessor commands
6.18 Summary

<--Prev page | Next page -->

 

6.11  'else..if'

The switch statement in C is relatively limited in the cases that it can act upon, even with the extension of ANSI C that allows switching on more than just int's. If one of a series of actions must be carried out, where one or more of the actions depends on more than a simple constant value of a variable, then multiple if..else if statements must be used:

 

if ( Ch >= 'a' && Ch <= 'z')
    ProcessLowerCase( Ch );
else
    if ( Ch >= 'A' && Ch <= 'Z')
        ProcessUpperCase( Ch );
    else
        if ( Ch > 0x7F )
            ProcessExtendedChar( Ch );
        else
            ProcessControlChar( Ch );

----------------------------------------

This follows indentation guidelines, but matching if's and else's can be very difficult. Even the use of braces would not help too much. In any case, the code rapidly tramps across towards the right hand margin.

Multiple choices are best treated as a special case, where the else if is treated as one keyword, and stays at the same indentation level as the original if. The final else prefaces the default case:

 

if ( Ch >= 'a' && Ch <= 'z')
    ProcessLowerCase( Ch );
else if ( Ch >= 'A' && Ch <= 'Z')
    ProcessUpperCase( Ch );
else if ( Ch >= FIRST_EXTENDED_CHAR )
    ProcessExtendedChar( Ch );
else
    ProcessControlChar( Ch );

 

How do you order these? Sometimes the order is natural. Sometimes, in a long list and especially if the comparisons are complex, then performance considerations may be important, and comparisons which are met most often will be put earlier in the list.

 

<--Prev page | Next page -->

 

Site Menu

| Home | Top | Settings |

Quality: | Quality Toolbook | Tools of the Trade | Improvement Encyclopedia | Quality Articles | Being Creative | Being Persuasive |

And: | C Style (Book) | Stories | Articles | Bookstore | My Photos | About | Contact |

Settings: | Computer layout | Mobile layout | Small font | Medium font | Large font | Translate |

 

You can buy books here

More Kindle books:

And the big
paperback book


Look inside

 

Please help and share:

 

| Home | Top | Menu |

© Changing Works 2002-
Massive Content -- Maximum Speed