Saturday, February 18, 2017

A C pitfall

Consider the following code:

#include ‹stdio.h›

int main(void)
{
 printf("This line ends with backslash (\\)\n"); // Print \
 printf("This is the second line\n");
 printf("This is the third line\n");
 return 0;
}

gcc 5.4.0 I have on my Xubuntu 16.04 box compiles this code without errors or warnings.
What do you think the code prints out when run?
This:

This line ends with backslash (\)
This is the third line

The second line is silently ignored by the compiler. The reason is that the line before it ends with backslash symbol (\). Even if the backslash belongs to the comment, gcc still considers the second line to be continuation of the line before it, and exactly because of this the second line is considered to be the continuation of the comment and is ignored.

Worst of all there's no warning or error, although ideone tells me that at least gcc 6.3 refuses to compile the code:
prog.c: In function ‘main’:
prog.c:5:50: error: multi-line comment [-Werror=comment]
  printf("This line ends with backslash (\\)\n"); // Print \
                                                  ^
cc1: all warnings being treated as errors

But anyway this is something to be aware of, especially if you're not sure about the way your compiler treats this case.

No comments:

Post a Comment