Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I'm sharing C# code with a fellow programmer who is more use to writing C++. He uses #if and #endif directives (which I do not tend to use) and when they occur they have no indentation, for example

        private void dumpToDisplay()
        {
#if false
            ushort[] ScanStatus = new ushort[6];
            for (int ch = 0; ch < 6; ch++)
                ScanStatus[ch] = mySteppers.GetStatus(ch);

            return;
#endif
            string dumpString = stepDump();

            Debug.Print(dumpString);
        }

It is interesting that the code sample in the #if C# documentation adopts the same convention and has no indentation for the #if and #endif directives. Is this important? It certainly makes them stand out, but is that good?

share|improve this question

2 Answers 2

up vote 6 down vote accepted

Is indentation of #if & #endif directives an important readability convention?

I think you mean outdentation (i.e. the #if is at the start of the line).

I'd say 'yes' because:

  • It's conventional
  • Unlike if statements, #if ... #endif statements don't use braces ({ and })
  • The contents of (i.e. lines between) a #if ... #endif don't have an extra indent (as they would inside an if { ... } statement)

It's also/more important for readability to have a language-aware IDE which:

  • Knows what preprocessor symbols are defined/redefined
  • Therefore knows whether each #if is true or false
  • And colorizes the text accordingly (e.g. grey for disabled text)

The Visual Studio IDE automatically moves #if statements to the left-most column. Any formatting which the IDE does automatically is, I assume, the best way to do it (if only because otherwise you're fighting with the IDE reformatting your code).

share|improve this answer

I think it makes sense this way, because the #if directives are pretty much outside of the normal syntax. For example, you can write something like:

#if DEBUG
    if (CheckConditionDebug())
    {
        DoADebug();
#else
    if (CheckCondition())
    {
        DoA();
#endif
        DoB();
    }

This is valid code in both states (DEBUG defined or not), but there is no good way to indent the directives.

Note: I'm not saying that this is a good use of #if, just that it is a possible use and that it makes sense to take this into account.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.