38 ms·
The //* /*/ //*/ comment toggle trick
- shin_lao 13y agoWhy don't you use macros? Additionally, source control tools make deleting code much more convenient, no?
- delinka 13y agoDuring debugging, there's often the need to temporarily disable a few lines of code to see the effect it has. I'm certainly not going back-and-forth with source control for something so trivial. That said, macros do make sense in this case- you can #define a single flag (e.g. FLAG) as a 0 or 1 and simply #if FLAG ... #endif, but it's certainly more typing to set up.
- shin_lao 13y agoIn that case I think I would prefer to use my editor's keyboard shortcut to comment out code, but that's a personal choice.
- huhtenberg 13y agoEveryone with a syntax highlighting editor discovers this trick sooner or later. Why spoil the fun of the discovery and post the solution? :)
- clearly 13y agoThis is terrifying!
- delinka 13y agoCare to elucidate?
- windsurfer 13y agoI think the poster might be referring to using finicky, unreadable line noise. Expressing program logic this was will inevitably lead to misunderstandings.
- majelix 13y agoIt's a fairly subtle way to dramatically change the behavior of your code. Frankly, it's a timebomb threatening to run testCode() in your production site. The low cost makes it useful for quick development, sure, but for stability's and sanity's sake, please remove when you start promoting this above your own playground.
- vowelless 13y agoThis should not be used. I would reject the code review if this came by me and recommend using ifdefs. Compilers are not uniform in their interpretation of nested comments.
- qompiler 13y agoI'm going slightly off-topic here, but I have to rant a bit on code reviews. For the love of god, please, they are meant for checking each others code for mistakes and not for miniscule details like this. I have seen it time and time again in various companies where code review is used as some sort of tool to dictate style and preferences to each other. Wasting valuable development time and creating a unhealthy tension between developers.
- vowelless 13y agoWhile I agree with you in general, in this particular case, we can run into problems when compiling the code on different platforms. Many teams/companies probably don't have a need for that. But I have been on cross platform projects where such errors would lead to days of wasted debugging time.
- deleted 13y ago[deleted]
- aleyan 13y agoIf code reviewers were just for checking mistakes, then unit tests would be enough. Code reviews are invaluable in education other developers about your code, how to support it and how to develop on it. But information should also flow the other way and the give the reviewers the opportunity to present the accepted practices to the developer. In the long term, this saves developer time as the code base stays coherent. Code is read many times and needs to be understood by many developers even though it is written only once.
- lotsofcows 13y agoIronically, that's the exact opposite to the way it works in my company. We use various automated techniques to pick up mistakes and use code review to ensure style is consistent. Everyone in the company should be able to parse any piece of code without individual styles disrupting that. The only tension occurs around the weighty question of line length - coding standard says 76 chars max, I say that's what the IDE's for.
- voyou 13y ago"This trick below can be used to toggle between two sets of code, with one symbol in the code with no additional short-keys to learn, and no tool dependencies!" So can #ifdef TEST / #ifndef TEST , which also has the advantage of not being horrific.
- Kurtz79 13y agoAgreed. That "trick" is a disaster waiting to happen, in a code base larger than a few hundreds lines of code.
- pygy_ 13y agoCue in Java, Javascript and PHP, which don't have preprocessor directives.
- deleted 13y ago[deleted]
- brokenparser 13y agoYes, yes, no. PHP is a preprocessor.
- aidenn0 13y agoUnless you run them through a preprocessor (which I recommend)
- mbenjaminsmith 13y agoI'm glad to know I'm not the only one abusing compiler macros for "ghetto source control". Having said that, there are plenty of cases where you can't use macros (like all languages/compilers/interpreters that don't support them). I don't agree with the author here though. Just comment the damn code out normally until you can clean everything up. Doing it that way encourages leaving that mess intact and forgetting about it.
- Lagged2Death 13y agoI don't think that counts as either "ghetto source control" or "abuse" and I'd be interested to find out why you feel this way. I mean, if you're talking about basic C, this (_DEBUG) is actually built-in to most systems from the get-go, for exactly this purpose. "Abuse?"
- deleted 13y ago[deleted]
- q_revert 13y agofor any vim users I would recommend having a look at NERDcommenter, from the author of the very popular NERDtree https://github.com/scrooloose/nerdcommenter https://github.com/scrooloose/nerdcommenter
- qompiler 13y agoIn Eclipse you can hit CTRL+/ to comment and uncomment a block of code you have selected.
- jrabone 13y agoOr CTRL+SHIFT+C to comment and uncomment a selection using single line comments. Or switch to block selection mode, make a multi-row zero-column selection and type // I love Eclipse.
- pattern 13y agoIn TextMate (OS X), a Cmd+/ does the same thing as well! To the author's credit, he does mention his hack has "no tool dependencies".
- lucb1e 13y agoIs it bad that I first saw this trick on NerdParadise.com?
- AshleysBrain 13y agoThis is a pretty cool trick, and I like that they shared it, but I don't think it's better than #ifdef!
- peterkelly 13y agoDijkstra is rolling in his grave right now
- snorkel 13y agoYikes. At least give the next coder that will maintain your code (and perhaps your future-self) a chance at understanding it. If the goal is to switch between prod and test code by flipping one char, then this works, too if (1) productionStuff(); else testStuff();
- jedbrown 13y agoYes, and this way the inactive code is still checked for validity and does not leave -Wunused-* warnings. Use `#if 0` if you want to disable code that is intentionally invalid, then grep your codebase for `#if 0` and delete those dead code blocks with extreme prejudice.
- user24 13y agoBetter way: /** testCode(); testCode(); /**/ (...) /**/ productionCode(); productionCode(); /**/ I think this is better because it's much easier to see what you're supposed to do in order to switch the block on or off, and it's only a single character change per block. (though you can't switch from test to production in one character, but meh). However, I tend to see commented code as ugly cruft. To me, comments are for explaining in natural language what you're doing, not for deactivating bits of code. If it's bad get rid of it, if it's good keep it. Why comment code? The only time I comment out code is to warn developers away from doing something which is obvious but a bad idea, for example: /* // This was a neat idea but it makes it break if the user isn't logged in userPreference = getPrefFromUserSession(); */
- scott_w 13y agoI think a better way of doing that is to create a test that fails in exactly that condition. You can then put documentation in that test, as that's what the developer will look at first. You also get the bonus that, if someone finds a way to fix the function that causes that, then you can go back to possibly nicer code.
- user24 13y agoThat assumes TDD, but yes that would be a nice way of doing it.
- Evbn 13y agoReading tests is not TDD, it is basic due diligene when learning code. Eve still, skipping that, when the test fails, the rush coder will see the problem.
- Evbn 13y agoThis is one of the many uses for tests that too few people know.
- pbreynolds 13y agoYikes at those extra slashes. I've always preferred this way: /**/ block one /*/ block two /**/ Simply add or remove the second slash to toggle.
- Twisol 13y agoI came up with this way when I started programming (and apparently had the gall to assume nobody else had done this...): /*/ test /*/ test //*/ Just add or remove the first asterisk.
- epo 13y agoThis is ingenious but if used in a work environment should result in instant dismissal.
- recursive 13y agoYou know you can use something for debugging without committing, right?
- wglb 13y agoLet's not do this.
- ryanthejuggler 13y agoI've been using this for a while in my JS projects. I'm about to start my first job as a web developer for a medium-sized company so I'm glad I came here and read all the backlash to this technique!
- yuvadam 13y agoCool trick. But there is no reason whatsoever to prefer this to a simple: git co branch Sorry. I've been burned one too may times from source-control-by-commenting-out.
- wldlyinaccurate 13y agoNo, no, no, no, no! This is a terrible idea, and will end up causing you a massive headache in the long-run. If I see commented-out code like this, I will delete it because that's what version control is for. If you really need to turn code on/off in different environments, you should be using feature flags: http://code.flickr.net/2009/12/02/flipping-out/ http://code.flickr.net/2009/12/02/flipping-out/ and at the very least you should be detecting the environment: if (ENV == 'dev') testStuff(); else productionStuff(); This is much more meaningful to other developers (and to yourself in the future).
- vorg 13y agoThis trick only works if there isn't a * / inside a string in commented out code (or there isn't a * / within the commented-out code itself in a language that allows such syntax, e.g. GrOOvy).
- Evbn 13y agoSad that the completely obvious fatal flaw in the entire premise is so far down the page here.
- mikeash 13y agoIf you actually commit this code to a repository I later encounter, I will find you.
- keefe 13y agocringe harsh, but fair. can't have this kind of idea spreading.
- Evbn 13y agoAnd since OP doesn't know how source control worms, he will never know how you found him.
- alexanderbrevig 13y agoYou're the one not knowing how to read and comprehend. This is a trick, I hope you learn some some day. My god this is tiring...
- npsimons 13y agoBetter yet, use a code review system, then automate a test that detects this and rejects outright any patch containing it. Sure, you can use this in your private repo, even keep it in your stashes/branches, but if it gets pushed to the central master, expect to be slapped down, hard.
- rplnt 13y agoSlightly relevant.. in an introductory C ourse at my university, we had to write a program that would tell us which version of the standard was used by the compiler. I can't think of a solution now but I'm sure it was based on different comment syntax.
- coherentpony 13y agoThis will compile to different things depending on whether you are using a C or a C++ compiler. Worse, it may compile to different things depending on which standard you compile to. If you don't want you colleagues to hate you, you should probably use: #ifdef DEBUG testCode(); #else productionCode(); #endif Or, better yet, if it really is test code then write a test.
- shubb 13y agoI don't understand why someone would do this nested comments thing. This is what macro block are for... And tests need to be separated from the code. Hopefully using a test framework. If your code changes depending on if it is in 'test mode' or not (which is what is proposed), then the test code is not the same as the production code, i.e. the production code is not tested. I'm not just talking about timing issues - extra variable names and objects will be in scope in 'test mode', and might logically change the behavior of the program.
- alexanderbrevig 13y ago* not all languages have macros * you don't use test frameworks for enabling and disabling code inline while you're developing Please read the protip, understand my intention (keyword TRICK) and have a delightful cup of coffee. You've earned it.
- B-Con 13y agoWelcome to Hacker News. :-) > understand my intention We don't do that here. However, we do have an unparalleled menu of pedantic critique, edge case obsession, and a wonderful sauce made from insanely perfect standards.
- deleted 13y ago[deleted]
- TheAnimus 13y agoOr just select the text and hit CTRL + K, C At least in my IDE anyway.
- benaston 13y agotldr: Don't do this.
- lnanek2 13y agoPlease just use if/else and a flag. It's much clearer and more maintainable.
- gordaco 13y agoI use this "trick" a lot, but I'll never ever dare committing it; just for small and quick checks (of the "what if I use this other implementation for the loop?"). If I'm going to commit, if (1) or #if (1) (plus a small comment explaining why I resort to that) are better options and immediately understandable for any other team member.
- diego_moita 13y agoDON'T DO THIS! When your code base grows you will end with dozens of places to change your code, all of them error prone. More things you need to keep control means more potential problems. There are 2 alternatives to this. For languages that have macros (C#, C, C++) use the #ifdef construct, as others suggested here. For languages that don't have them (Java, Perl) use a less error prone alternative: static boolean Test = false; // Only one place to change code ... if(Test) doTest(); The difference in this last technique is that since you have just one place to change code there is less chance for errors and the change is easier to automate.
- alexanderbrevig 13y agoI'd appreciate if you'd have this discussion on Coderwall. That way I could 'defend' the post where it's due. However though, please read https://news.ycombinator.com/item?id=5626456 https://news.ycombinator.com/item?id=5626456 and summary is: It is a trick, not a silver bullet. It prevents code from being compiled to the binary, in a portable - yet hacky - way.
- SoftwareMaven 13y ago#define DEBUG 1 #if DEBUG test_code() #else real_code() #endif Much more readable and the DEBUG macro can be defined in a common header, so all of the code can share it. The comment trick isn't useless during development, but I'd see myself using a macro rather than trying to remember just where a slash goes.
- alexanderbrevig 13y agoRun that with vanilla JavaScript, Java, SQL or anything but C/C++ [this is the premise of the protip] and I'll bake you a cake! (One that's not a lie;) Nothing that's discussed here does the same thing, though I completely agree there is a lot of better techniques for various tasks, nothing is functionally the same as the trick. (Why can I not reply the the reply of this post? I'm new here.)
- alexanderbrevig 13y agoI understand the criticism, it's not supposed to be _the_ way to toggle code in and out. It's a TRICK, and that's all it will ever be. However, it is the only way I know of that is not language specific for a particular dialect of C (#ifdef) that enables code to _not_ become a part of the compiled binary, or in JS terms - not available from the runtime. Best regards -OP
- mkadlec 13y agoI never liked this kind of code practice, makes it very difficult to read!
- akamaka 13y agoWhy are there so many angry comments on this thread? I use this sort of trick all of the time when debugging, but I rarely commit any commented out code as a matter of principle. Nobody was suggesting using this for "ghetto source control" or that this is an alternative to compiler directives. Can't we just be polite and say "Cool hack, but obviously don't commit this type of code", instead of getting out the pitchforks?
- taoufix 13y agoAgreed. I use commenting/uncommenting a lot when debugging. This trick makes it easier.
- laurentoget 13y agoYou and I may know this should never be committed. Hundreds of students and junior developers will read this post and need to be warned that this is a VERY BAD IDEA. I would rather make angry comments here than to have to explain why this is a terrible idea in a code review of an intern or a junior colleague.
- vowelless 13y agoPersonally, I think the comments highlight why this can cause problems and what the alternatives are. Knowing the trade-offs and then choosing an approach is good design. Feel free to use that hack, but be sure you know what the trade-offs are, and what bugs can potentially arise in the future due to this hack.
- tlrobinson 13y agoFirst thought: cool trick! Second thought: oh boy, Hacker News is going to have a field day with this one.
- HardyLeung 13y agoAs a long-time C++ developer I wish people don't use any commenting tricks such as this, and I wish people don't use /* * / to comment their code, even if you develop in C. Instead, use // in modern C/C++. The reason is that we often need to comment OUT code during development. In C++, the 4 choices are: (1) #ifdef, (2) bool dothis = false; if (dothis) { ... }, (3) /* * /, (4) // ... Among them, I would say the best and least-confusing way to comment out a block of code is /* * /. #ifdef's are very confusing especially if you have multiple of them; // needs to be applied to every line so only works in small scale; if (dothis) doesn't work across multiple functions, and at a glance it is harder to discern whether this is a "comment-out", or a legit condition. However, by using /* * / in your comments, you eliminate the possibility of commenting out blocks of code that contains /* * / comments. The problem, of course, is due to how the opening and closing symbols are matched.
- alexanderbrevig 13y ago"I'd appreciate if you'd have this discussion on Coderwall. That way I could 'defend' the post where it's due. However though, please read https://news.ycombinator.com/item?id=5626456 https://news.ycombinator.com/item?id=5626456 and summary is: It is a trick, not a silver bullet. It prevents code from being compiled to the binary, in a portable - yet hacky - way."
- wting 13y agoSome C projects still use -ansi and thus C++ comments (//) will result in a compiler error.
- mzs 13y agoI've adopted: #if 0 /* reason / lines of messy stuff ... #endif / reason */ That short comment makes it easy for me to find the ends.
- mzs 13y agoHa, I thought I put in the asterix-esses. You know what I mean, but I bet cpp actually ignores e everything after #if 0 and #endif, don't do that please ;)
- lambda 13y agoWhy would you do this instead of #if 0/#if 1? Has exactly the same effect, is a one character toggle (sure, it's editing one character rather than inserting/removing one character), and is much easier to read and remember.
- laurentoget 13y agoworse idea ever. if you need to have branches in your code, learn how to use your source control environment. even cvs lets you branch your source tree.
- alexanderbrevig 13y agoThis is not an attempt at branching, this is a trick. The protip is not to use the trick, but to know about it. Read the tip, try to understand the intention - then criticize. Thank you kind sir.l
- noptic 13y agoThis is a nice trick for quick comparison and thats it. I actually use this a lot for performance comparison. This way it is easy to toggle between the olt d and the new implementation and see how long it takes to run the code 1000 time in javascript. But I think anyone who check ins something likes this should be slaped.
- alexanderbrevig 13y agoThis is exactly what this trick can be used for. Thank you for voicing your opinion. Happy coding!
- npsimons 13y agoThis seems . . . silly. I mean, honestly, do code editors besides Emacs not have something similar to comment-dwim?
- deleted 13y ago[deleted]
- sriram_malhar 13y agoCute trick, and lovely addition to the Obfuscated C code contest. Not for code to be used by anyone else (or by yourself after a few months). Reminds me of another trick for debugging C++ programs. This allows you to dump data structures easily: #define private public include <foo.h>
- JoshTriplett 13y agoFun related trick: $ cat test.c int compiler_supports_single_line_comments = 1 //* //*/ 2 ; int main(void) { return compiler_supports_single_line_comments; } $ gcc test.c -o test && ./test ; echo $? 1 $ gcc -std=c89 test.c -o test && ./test ; echo $? 0
- Twisol 13y agoThere's a slightly less-interesting Lua analog as well: --[[ Code block one --[=[ Explanatory comment here ]] Code block too --]=]
- CyberDroiD 13y agoI like 'Code Opinion Blogs'. Interesting insight into what people prefer when coding!
- wting 13y agoRather than relying on syntax tricks, I'm sure most editors allow for block commenting or comment inversion. For example with NERD Commentor vim plugin, you can toggle block comments with `<leader>c<space>`. Inverting comments is `<leader>ci`. https://github.com/scrooloose/nerdcommenter https://github.com/scrooloose/nerdcommenter
- DalekBaldwin 13y agoIn Python: #''' some_code() ''' some_other_code() #''' ... with one character toggled, becomes: ''' some_code() ''' some_other_code() #''' If you work with anyone who says "Don't do this," don't do this.
- huyvun 13y agoon non-gcc compilers this is valid #define include_them 1 #if (include_them==1) #define hotcode /##/ #else #define hotcode #endif void func (void) { hotcode printf("if included_them true, compile this line"); }
- dbbolton 13y agoA much more elegant solution is to use Commentary[1] in Vim (and I'm sure there's an emacs equivalent too). Just use visual mode to select your text, hit `gc`, and voilà. 1. https://github.com/tpope/vim-commentary https://github.com/tpope/vim-commentary
- NotDaveLane 13y agoDependency injection[1] would be preferable. Alter behavior based on defined environments (dev, test, staging, production), not whimsy. [1] http://en.wikipedia.org/wiki/Dependency_injection http://en.wikipedia.org/wiki/Dependency_injection