📜 ⬆️ ⬇️

Shutting down the code comment: small life hacking

Despite the simplicity (and, in general, the triviality, if you think) of the solution described, I came across it purely by chance, while decorating a finished program, ready for delivery.

In programming practice, a situation regularly happens when during development and debugging it is required to turn on some code and turn off another. It is easy to do with special constructions like #if true ... #else ... #endif , changing true to false , or resorting to more sophisticated conditions. However, this design does not allow to create more than two alternative sections of code.

In languages ​​that support a comment like /* ... */ using a slightly non-standard construction /**/ ... /*/ ... /*/ ... /**/ you can create as many alternating sections of code that will be alternately turned on and off with just one space in the first (starting) comment.
')
For example:

 /**/ Console.Write("1"); /*/ Console.Write("2"); /*/ Console.Write("3"); /*/ Console.Write("4"); /**/ Console.Write("5"); 

When executed, this code will output the string "135" to the console. That is, all odd inference operators will be executed - and the last one, which is already outside the whole structure. But if you insert a space (or, strictly speaking, any character except an asterisk) in the starting comment between the second asterisk and the slash, the same code will print the string "245" : only even operators will be executed, and, again, the last one already outside. (UPD: thanks to FluffyMan for pointing out the error).

The syntax of the separator comments is extremely strict: nothing can be subtracted to the /*/ construction, nor can it be added, this will destroy its functionality. The syntax of the start and stop comments is completely arbitrary. It can be minimalistic to /**/ , and it can contain any kind - legal in the sense of the language - comments. From where it is clear that start and stop comments are strictly obligatory, and that within the construction itself it is simply impossible to use a legal comment like /* ... */ since it immediately becomes a stop for the entire previous sequence of comments / delimiters /*/ , and starting for the entire subsequent sequence. But sensible use of such inserts may be useful.

Single-line comments // do not affect the functionality.

Dixi :)

Source: https://habr.com/ru/post/434300/


All Articles