Search code examples
cwhitespaceremoving-whitespacetrailing-whitespace

Is it 100% safe to strip trailing whitespace from .c/.h source files?


I'd like to automate removal of all trailing whitespace from .c and .h files, to reduce garbage that causes merge conflicts in git history, etc.

Is there any conceivable way this could change the output of the compilation stage? Or is it perfectly safe to do this automatically?


Solution

  • The only case I can think of where this could change the meaning is if there's a macro that ends with backslash followed by spaces:

    #define FOO bar\<space> 
    

    where <space> represents a space character. Before trimming, the backslash escapes the space, which I don't think has any effect. But when you remove the space it escapes the newline, so the next line will become part of the expansion.

    Since there's no reason to write an escaped space like that, this seems like a very unlikely problem. In fact, if there's code that looks like this, I think it's more likely that they intended to write a multi-line expansion, and the space was added by accident.

    Outside macros and string literals, all sequences of whitespace are treated as a single space, and there's no difference between spaces and newlines.

    UPDATE:

    This case isn't actually valid. C doesn't allow escape sequences outside string or character literals, and only newlines can be escaped with backslash. GCC has an extension to treat this as an escaped newline (in case the programmer made the mistake I describe above), and it prints a warning when it's doing it. So removing the spaces will produce the same result but get rid of the warning.