I have programmed C for quite a while now. During this time I have learned that it is a common convention to put the "#"-character that comes before preprocessor-directives at column one.
Example:
#include <stdio.h>
int main(void) {
#ifdef MACRO1
#ifdef MACRO2
puts("defined(MACRO1) && defined(MACRO2)");
#else
puts("defined(MACRO1)");
#endif
#else
puts("!defined(MACRO1)");
#endif
return 0;
}
When people indent their preprocessor directives they usually do it like this:
#include <stdio.h>
int main(void) {
#ifdef MACRO1
# ifdef MACRO2
puts("defined(MACRO1) && defined(MACRO2)");
# else
puts("defined(MACRO1)");
# endif
#else
puts("!defined(MACRO1)");
#endif
return 0;
}
I do not think that I have ever seen anyone format it like this:
#include <stdio.h>
int main(void) {
#ifdef MACRO1
#ifdef MACRO2
puts("defined(MACRO1) && defined(MACRO2)");
#else
puts("defined(MACRO1)");
#endif
#else
puts("!defined(MACRO1)");
#endif
return 0;
}
My question is if the C language standard demands that the #
-character should be in column one.
So is the third option above even legal?
If all above cases are legal then I want to know if this is legal.
#include <stdio.h>
int main(void) {
#ifdef MACRO
puts("defined(MACRO)");
/* Now there are other characters before the `#` */ #endif
return 0;
}
Here is the #endif
no longer on the "start" of the line because there are other non-whitespace characters in the way.
What seems weird about the last example is that Vim
text-editor does not highlight the #endif
that comes after the comment.
All these examples I have given compiles without any warnings using gcc
with the -Wall -pedantic
flags turned on (including the last one with a comment before #endif
).
Note that I am just curious about the syntax. I always put #
-character at column one like everyone else when I program. I would never write things like ++i; #endif
in serious projects.
#
and the directive name, I always make sure the#
and directive name are attached, and just put whitespace in front of the#
instead. It works fine. – Tutorc-preprocessor
tag forlanguage-lawyer
, as you're asking a specific question regarding the standard. The pair ofc
andpreprocessor
should suffice, and the added tag might reduce the tendency to downvote and/or vote to close. If you object to the change, please feel free to roll it back. – Antinomygcc
using-Wall
and-pedantic
. It compiled finely without any warnings. Like Keith pointed out I want to know what the standard guarantees, not what works withgcc
. – Lovage