fun with comments
Date: Message-Id: https://www.5snb.club/posts/2023/fun-with-comments/
Tags: #hack(6)
Programming languages typically include one or two ways to comment out code so that the compiler doesn’t read it. One being line comments, such as
foo(); // comment here
which will comment out any code up until the end of the line, and the other being block comments, such as
foo(42 /* a
good
number */ )
which will comment out code in a block.
Block comments aren’t restricted to
a single line, and can sometimes be nested (so that /* /* */ */
behaves
correctly).
But what happens when you mix the two?
Well, if you comment out a block comment directive with an active line comment, then the block comment does not apply. This can be seen most simply with
fn main() {
// /*
*/
}
error: expected expression, found `/`
--> src/main.rs:3:6
|
3 | */
| ^ expected expression
Here, the block comment didn’t actually start. Which makes sense, it’s in commented out code.
But active line comment there is important. If a block comment did start, then the line comment does not apply, only block comments do.
fn main() {
/*
This is commented out
// */
but_this_is_not();
}
The //
does not matter, because it’s commented out.
Therefore, if you want to end a block comment if it exists, otherwise do
nothing, then you can do // */
. That line comment will be active if you’re
not currently in a block comment (in which case the */
is just part of the
comment), or it will not be active, but it will be commented out, in which case
the */
is active and removes a nesting level.
This means that if you have a large code span that you want to quickly comment
out and uncomment, you can put a /*
at the top, a // */
at the bottom, and
then replace the /*
with a //*
with a single slash.
fn main() {
//*
this_is_no_longer_commented_out();
// */
and_this_is_not();
}
I have used that in the past when I don’t have IDE shortcuts. Useful? No, not really. But a fun hack.
Finally, if you want to switch between 2 different functions with a single
keystroke, you can put a function on the same line as the // */
line, and
make use of the fact that the line comment is conditionally active.
fn main() {
//*
a();
// */ b();
}
fn main() {
/*
a();
// */ b();
}
a()
can be multi-line, but I don’t think there’s a way to let b()
be
multi-line.