C/C++ Source Code Formatter
Preprocessor Constraints

The C formatter and the C++ formatter both fully parse the source file, retaining comments, macros, and preprocessor conditionals. Some source files are difficult to parse without expanding directives or macros, generally because they violate a clean nesting structure of the source code. The DMS parsers for C and C++ accept many commonly occurring "unstructured" preprocessor constructs, and so this problem is less pervasive than one might think.

For example, it is quite common for preprocessor conditionals to be wrapped around C-style control-flow structure headers on a header-line by header-line basis:


    #if ppexp
        if (condition1) {
    #else
        if (condition2) {
    #endif
        ifbody }

The formatters can handle this typical case and many others like it without trouble, and preserves this "structure" in the formatted output.

Some more unusual unstructured constructs cannot be parsed properly. The formatters will clearly diagnose these with format-time syntax errors. To format source files with such constructs, some slight editing of the source may be needed once to ensure such conditionals are properly nested. (We think this generally improves the readability of code regardless of how it is formatted). The following is an egregious example of bad structuring:


    if (condition) {
      then_statements
    #if ppexp
      } else {
    #endif
      else_statements }

This example can be fixed by the following slight, one-time permanent source file fix:


    #if ppexp
    if (condition) {
      then_statements
      } else {
      else_statements }
    #else
    if (condition) {
      then_statements
      else_statements }
    #endif

If the else_statements have significant size, they can be placed into a macro to avoid duplicating a large block of code. Other cases are generally similar and easy to fix.

The formatter documentation discusses in this more detail and shows more examples. The formatter also uses hints about what is defined as a macro, and can automatically pick up these hints from the source's designated header files, or from a user-configurable custom file.

For more information: info@semanticdesigns.com    Follow us at Twitter: @SemanticDesigns

C Preprocessor
Constraints