syque.com

The Psychology of Quality and More

| Menu | Books | Share | Search | Settings |

C Style: Standards and Guidelines (contents)

CHAPTER 8 : Language Usage

PART 4 : USAGE

CHAPTER 8 : Language Usage
8.1 General principles of language usage
8.2 Using expressions
8.3 Using 'if'
8.4 Using 'while'
8.5 Using 'for'
8.6 Using 'do'
8.7 Using 'switch'
8.8 Using 'goto'
8.9 Using 'continue' and 'break'
8.10 Using 'return'
8.11 Using functions
8.12 Using '#define'
8.13 Conditional compilation
8.14 Other preprocessor commands
8.15 Summary

<--Prev page | Next page -->

 

8.13  Conditional compilation

The #if and #ifdef statements allows conditional compilation, which can be used, for example, to embed debug code or to enable different sections of a program which is to be ported to several different environments:

 

#if LANGUAGE == ENGLISH
    printf( "Hello, world\n" );
#elif LANGUAGE == FRENCH
    printf( "Bonjour, monde\n" );
#else
#   error "valid LANGUAGE not defined"
#endif

 

This may make it easy to compile different language versions, but it makes the code difficult to read, as what is effectively one statement has become a more complex block. The complexity in this type of usage can sometimes be moved elsewhere:

 

/* messages.c */
...
#if LANGUAGE == ENGLISH
    char *Messages[] = { "Hello, World", ...
#elif LANGUAGE == FRENCH
    char *Messages[] =

 "Bonjour, Monde", ...
...

/* messages.h */
#define HELLO_WORLD 0
...

/* prhello.c */
#define LANGUAGE ENGLISH
#include "messages.h"
...
printf( "%s\n", Messages[HELLO_WORLD] );

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

Note that #elif and #error are ANSI C keywords. A backwards portable approach would be to use a sequence of #ifdef..#endif.

 

#ifdef (or #if defined in ANSI) is typically used in a similar manner to #if, conditionally enabling portions of code.

 

#ifndef is typically used to flag an error or provide default values where a symbol has not been defined:

 

#ifndef BUFFER_SIZE
#define BUFFER_SIZE 256
#endif

 

<--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