Sunday 4 May 2014

Single-line comments that want to be multi-line

Update: While working on this code today, I had some "mystical" results, and ran a rebuild instead of the usual build. Et voilĂ , gcc presented me with this: "warning: multi-line comment [-Wcomment]". So, in all fairness, this issue isn't as much of an issue as it appeared at first.

So, we have our good-ole multi-line comment, aka, C comment:

/* I am a long comment, spanning a lot of lines,
I just go on and on until I start foaming at the
mouth and falling over backwards, and...
I say, I seem to have drifted a bit, haven't I...? */

Then, we have our heavy-duty single-line comment, aka, C++ comment (actually, since C99, this has been a bit of a misnomer): 

// What do we mean by no?
// What do we mean by yes?
// What do we mean, allowing backslash \
line continuation to work on single-line comments? \
Why?

Oh, yes, this will happily compile. Let's see it in action, in a terribly contrived example:

int main()
{
    // We don't pass any argument to CountFiles()
    // because we always start at \
    int tot_files = 0;
    tot_files = CountFiles();

So, our intrepid - and rather uncognizant - developer documents the design decision to always start counting files at the current drive's root. Developing on the Windows side of C++, and being eco-minded, he decides to save 3 characters by replacing "root" with "\".

The compiler (in this case, gcc) rewards him with this beautiful message: "error: 'tot_files' was not declared in this scope".

In all fairness, VC++ correctly flags the continuation lines as comments, the "syntax artists" responsible for painting our IDEs in all those lovely colours correctly paint those lines as comments. Qt Creator? Not so much, as you can readily see from the code snippet above. Not that I blame them, really; I imagine they have more important things to do.

Reading about it, I learned this behaviour occurs because continuation lines are eliminated (i.e., the backslash and the newline are removed, thus joining the lines together) before comments are removed.

I find this a bit strange. It would be more sensible for the first step to be comment removal. Which would have the beneficial side-effect of getting rid of this brilliant rule (in the "brilliant bean" sense, I mean) .

Yes, I know, there are more important things to do.
 

No comments:

Post a Comment