0

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?

endolith
  • 25,479
  • 34
  • 128
  • 192

1 Answers1

5

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Not necessarily macro. Any line with backslash: https://ideone.com/pvcrYS – Eugene Sh. Apr 30 '21 at 18:56
  • 1
    If there's a space after your backslash, the code is invalid, since raw newlines aren't allowed in string literals. – Barmar Apr 30 '21 at 18:58
  • 1
    Your code doesn't have a space at the end of that line, so there's nothing to remove. – Barmar Apr 30 '21 at 18:59
  • Yeah, you are right, bad example. Can't think of anything similar where additional space will make it valid and change the meaning. – Eugene Sh. Apr 30 '21 at 19:01
  • This produces the warning `backslash and newline separated by space` and C90 apparently prohibits it? GCC treats it as a continuation character: http://gcc.gnu.org/onlinedocs/gcc/Escaped-Newlines.html#Escaped-Newlines – endolith Apr 30 '21 at 19:29
  • 1
    You're right, so I think there's no actual cases where the behavior is changed. – Barmar Apr 30 '21 at 19:36