Tuesday, November 10, 2020

Abusing C-Style Comment Syntaxes For Fun (and Profit)

C originally only had multi-line comments, which work like this:
/* no comment */
All characters between the /* and the */, including newlines, will be ignored by the compiler, and you're free to document your code as you see fit.  People eventually got tired of typing */ and thus the syntax // for a single-line comment was born.  Interestingly, we can abuse a combination of both comment syntaxes to easily toggle between two alternate blocks of code with the addition or removal of a single character.

Feast your eyes upon this abomination:
/* code block 1 /*/ code block 2 //*/
In that example, code block 1 is commented and code block 2 will run.  However, add a single slash at the beginning:
//* code block 1 /*/ code block 2 //*/
Now code block 2 is commented, and code block 1 will run instead.

This works because when the beginning is /*, it begins a multi-line comment.  The /*/ ends the multi-line comment, and //*/ is a single-line comment.  When the beginning is //*, it's a single-line comment.  The /*/ begins a multi-line comment, and the //*/ ends the multi-line comment.

Have a nice day!

No comments:

Post a Comment

I moderate comments because when Blogger originally implemented a spam filter it wouldn't work without comment moderation enabled. So if your comment doesn't show up right away, that would be why.