programming

Lisp in Python

This is definitely the coolest programming related text I’ve read in a long while: Church Encoding in Python. I even almost understood all of it! :D
I saw this on the Planet Python feed aggregation(?) (it is the second entry right now) which I got introduced to today.
But seriously, how cool is the CONS construction and number encoding stuff?!

VN:F [1.0.8_357]
Rating: 7.0/10 (3 votes cast)

code
cool
programming

Comments (0)

Permalink

How Much We Spend Waiting for Our Tools?

By
Absolutely no comment!

VN:F [1.0.8_357]
Rating: 7.0/10 (3 votes cast)

Quotes
hilarious
programming

Comments (0)

Permalink

Fun with C++: Useless Consts?

Many C++ programmers see the keyword “const” as something redundant that only gets in the way. They curse Stroustrup and his ancestors each time they encounter a const-related compile error because of that view and fail to use it correctly quite often (note that I’m not saying that I’m not one of these people, but I curse neither Stroustrup nor anyone else.)

If you ask them about the purpose of the const keyword, they would give you the classic answer that any C++ textbook gives: variables declared as consts cannot be changed by the programmer, and const class methods cannot modify their instance data (and can be called on const class instances), etc.

The programmer may give you the textbook answer (or some mutilated version of it, depending on which textbook she read and how much of it she actually remembers,) but she is wondering with herself who will stop the other programmer to change the header file and remove the const from the declaration? Who is there to prevent her from doing so?!

She may even make a conjecture that if she removes all the consts from all her source files and headers (including standard and 3rd party headers she uses,) then her programs will continue to compile and work just fine (after all, the const keyword has no runtime effect. It’s an exclusively compile-time construct, is it not? So if her programs used to work, and they compile after removing all consts, they should continue to run without problem.)

If she is a little bit more sophisticated and skilled in C++, she knows that the C++ compilers differentiates between functions that take const arguments and those that take exactly the same arguments, but not const. This fact lets you have function overloads that only differ in constness of their arguments. The same is also true for template specializations (which is a form of overload anyway.)

So this more sophisticated C++ programmer will conjecture that if she removes all the consts and eliminates the redundant overloads (which were nothing but nuisances to begin with) then her programs will compile.

Now, is she right? Is this the case with const?
(I should say that I know of one case that is not so (the program will not compile without the the const) but it’s not a common case. I’ll write about that in a later post (if no one guesses it first.) I’m genuinely interested in other such cases.)
(Another note. The use of const frees the compiler to do some optimizations that may not be safe with a non-const object. My question is about correctness and not about performance.)

VN:F [1.0.8_357]
Rating: 5.5/10 (2 votes cast)

C++
code
programming

Comments (2)

Permalink

C++ “Glasses”!

The Slashdotters put together a list of questions for Bjarne Sroustrup to answer a while back. The Q&A is interesting on its own, but this comment by an anonymous coward (as they are called on /.) is the funniest piece of writing I’ve read in a long time!
Read the Q&A and the rest of the comments too, if you have time.

VN:F [1.0.8_357]
Rating: 5.5/10 (2 votes cast)

C++
hilarious
noteworthy
programming

Comments (3)

Permalink

Java Ruining the Programmers of Tomorrow?

Read this post on slashdot, and this article that the post references. The comments on the /. page is interesting as well.
In short, we all know that today’s university graduates learn very little about programming and software architecture that has real value from their curriculum. This article focuses on the problems of high-level programming languages, but the reverse is equally true. Again we have all seen old-timers who can code in assembly and C, but are still struggling to grasp this “new” concept called Object-Oriented Programming!
I’m sure that for great programmers, a language is just a window, and not their eyes. They can use a different window in the other wall if the current one does not offer the view they desire or has the wrong-colored glass panes, but for the rest of us, our programming languages pretty much define what we consider easy/hard/fun/boring (if not possible/impossible.)
That’s one of the reasons I like and prefer C++. It hides almost nothing of the complexities and idiosyncrasies of the underlying machine (which can be a pain, or an opportunity) while still letting you solve, or at least manage, the pains and take advantage of the opportunities. It’s mighty complex and full of dark corners and dirty tricks, but you can get the job done, on any level you want, as close or as far as the bare metal as you want.
In short, C++ rocks!

VN:F [1.0.8_357]
Rating: 5.5/10 (2 votes cast)

programming

Comments (12)

Permalink

Games, Games and Games

Games are interesting, and game programming is even more interesting.

  • No one understands it, in a traditional context. You can tell your family that you are writing navigation software for spy satellites, but not games. If you have moving graphics on your screen, then you are playing games and wasting your time. Note that it’s even a level harder than just playing games which you can (in theory) explain as just passing time (which is quite unsuccessful in practice,) but actually trying to create a game is the most foolish thing anyone can do. Why can’t one stick to more reputable jobs like robbing graves or more successful ones like becoming an alchemist?
  • It’s exciting. Not only you get to create something, but you get to play it too, and other people get to play it. It’s the most complex and advanced form of performing arts: theater, cinema, puppet shows. And it’s interactive, like a stand-up comedy act, but with cooler characters. The most comparable medium is cinema, but computer games put emphasis on technology mostly, while in cinema it’s supposed to be on art.
  • It’s the most misunderstood of the media. No one but a semi-serious gamer understands the lure and pull of games, absolutely no one. It’s not a sport. It’s not education (it’s not, trust me!) It’s not even just for fun, most of the times. It’s not a professional job. It’s not serious. It’s nothing. It’s too complicated most of the time for an outsider (and sometimes for an insider!) to pick up gaming so everyone who’s not played video games as pre-teens or young teenagers is pretty much already out of the loop. There are so many bad games that even if one wants to understand what’s what in games, (s)he may get a totally wrong image.
  • There’s money in it, but not where everybody can see it. I don’t have any numbers now, but I think it was in 2005 or 2006 that the world game industry became bigger than the world movie industry, in terms of financial investments and revenues. The growth of the game industry have always been faster than the movie industry so the distance will become even more drastic over the next years. But people see rock stars and movie stars who live the high life, but no one notices a bunch of game designers, programmers and game-company managers with lots of money.
  • A lot of people want to make games. Every half-decent programmer writes a game at one point or another in her life. Every programmer thinks about writing games. Every 3D artist thinks about it. Every programming company owner thinks about it. Every university student wants to do it.
  • A lot of people fail to make games. We’ve all heard stories of defeat and failures and deadlines that were never met and bankrupt companies or just a group of fiends who tried to make games. If we are lucky enough, we don’t get to experience that first hand.
  • Games require many different people to work with each other in harmony. Managers, graphists, environment designers, writers, 3D modelers, animators, 2D painters, level designers, game designers, mechanical engineers, programmers of many different creeds, directors, actors, sound engineers, producers, and many more have to work together on a project that almost none of them understand fully to make it through. It’s like a movie production, a modern movie with lots of special effects, but with a lot more programmers and a lot less actors. This is a bad thing. Remind me to talk about actors and programmers more later!
  • Games need many different branches of programming to work. A simple database driven program requires database programming, and UI programming, and software engineering. Games require software engineering on steroids (you have to deal with all the artifacts and workflows and dataflows for the rest of the team (artists, designers, etc.) too, to say the least!) database, network, UI, real-time graphics, simulation, math, AI, computing theory, geometry, low-level system programming, sound, concurrent programming on many levels, etc. etc! Almost everything a programmer can think about programming of is either already used in games or will be. Very few programmers can master all this. In fact, very few programmers can master one of these fields.
  • Add to the above the fact that games need to do all of this really fast! Frame-rate and user experience is everything. You can’t afford to get lousy and put some routine in your game engine without understanding its trade-offs and performance and resource usage patterns. In an office application, no one will notice if the performance of your application drops down 50%. But everyone will notice if their game is running at 10 fps instead of 20, or at least they will get headaches if they don’t notice otherwise. High-throughput (bytes per second, frames per second, triangles per frame, texels per frame, instructions per second, cache misses per memory accesses, etc.) and low latency are the keywords. There’s always something per something else that needs to be maximized or minimized or even kept even over time. It’s a hard business. Trust me.
  • All the factors above make games hard, really hard. And they also make them challenging.
  • Academics hate games. They look at them as the useless byproduct of juvenile stupidity. You can’t catch a respectable university professor working on games. Even academic papers that are directly related to games (rendering, network, complexity management, etc.) are all written under an excuse, for another field (image processing, physical simulation, load-balancing servers, etc.) This trend is changing however. It’s becoming better for game programmers in the academic sector.
  • Idiot politicians (or generic idiots) want to use games for education! This is one of the more ridiculous notions a gamer encounters in her life. Who plays games for education? Absolutely no one. Pay attention to my lips people: NO ONE PLAYS GAMES TO BE EDUCATED. If you aim to make educational games, you will make crap that no one will play except yourself, and you will kill your own brain cells in the process. Even the most controversial games have educational messages, but no one plays games to get educated. Why is it so hard for people to really, deeply understand that entertaining people is worthy on its own. And that if you want to educate people, first there must be someone listening to or looking at you in order for you to educate them.
  • There’s no game industry in Iran. We don’t have the supporting sub-industries like motion capture or FMV creation shops, the professional game publishers and the like. We don’t teach game programming in our engineering schools, and we don’t teach game art or game writing in our art and literature schools. We don’t have game companies to train newcomers into professionals for the next generation. And most importantly, we don’t have the legal foundation to support corporate media and software industry, and games are a sub-class of both.
  • Games have the worst possible kind of user-base. They are in every age. They have every imaginable level of computer skill (but they are mostly total lusers.) They have absolutely no training, and there can be none. No one reads game manuals and no one expects to have to. You can’t hold training seminars and classes for games. Users have every kind of hardware imaginable. If you refuse to run on their machine, they won’t upgrade their machine for your software, they will just by another game (unless you are “id Software” or “Epic Games” or “Crytek”.) They will push every button in every possible place during the lifetime of your game. They won’t have any patience with your software. They won’t read the message boxes on screen before clicking on “OK”. They will become frustrated and lose interest after the second glitch.
  • Competition is pretty fierce in among game titles. Games not only have to compete with other games, they also have to compete with other forms of entertainment. Also, other software only have to compete with their own kind. Word processors compete with word processors and disk defragmenters with disk defragmenters. But games compete with all other games almost regardless of their genres. Even platform is sometimes irrelevant to competition.
  • Games always live on the bleeding edge of technology. They have to. Many of the advancements in technology are driven by entertainment money and games are the prevalent form of entertainment. Games have to be on the edge because other games are, and they can’t afford to look “out-dated”. Also, there are always new ideas the designers or programmers or artists want to try that absolutely requires that state-of-the-are CPU or GPU or whatnot.

Those are some the reasons that make game programming interesting.

VN:F [1.0.8_357]
Rating: 1.0/10 (1 vote cast)

entertainment
programming
rants

Comments (11)

Permalink

OpenID, a Neat Idea

If you’re anything like me (wait, that’s not an insult!) you live a busy life online. You have a multitude of registrations and user IDs and passwords for many sites on the net. There are many ways to manage this inherent mess with different trade offs between convenience and security.
One methods that I came across recently is using an Open ID (here’s the Wikipedia page.) I first saw this when leaving a comment on a Blogger weblog. I noticed that one of the authentication methods it supported was a single URL, and the caption read “Open ID”.
Well, suffice it to say that after a couple of hours I had my own personal Open ID provider up and running, using phpMyID. Even if you don’t have an Internet-reachable box at your disposal, you can use one of the free ID providers (listed on the above pages.)
I’m yet to investigate the security of the whole system in depth, but it seems well enough. In the least, it let’s me be in charge of my own security instead of some random web site.
But such a scheme does not work if it’s not adopted, not by users, but mainly by software developers. As a developer, I’m going to consider giving the users of my next web-based application (if I ever develop such an application again) the option of logging in using their Open ID. I hope others do so as well.

VN:F [1.0.8_357]
Rating: 1.0/10 (1 vote cast)

noteworthy
programming
sci-tech

Comments (0)

Permalink

Unguaranteed Order of Pre-main Object Initialization in C++ - Any Solutions?

The C++ standard leaves the relative initialization order of global and static data undefined. The only thing that the compilers must guarantee is that all such data have been initialized before the invocation of main(). In any large and well-designed project, there are no or very few global objects. But static member data in classes are unavoidable in many occasions.
The unspecified and unguaranteed relative order of initialization of these objects can lead to undesirable effects. You could very well end up using objects that have not been initialized yet.
This is my problem. I’m in the design stage of a large library, and I want to know any thoughts or useful material you might have or have seen relevant to this problem. (This library is a game engine, by the way, and we will be delighted to have anyone with enthusiasm and technical expertise on board with us.)
One solution that comes to mind is doing all the initialization of static object in functions (for example, one per each class with static data members) and “registering” these functions and their relative priority at the static initialization time (before main()) but do not invoke them then. The only static object that is actually initialized pre-main is the object that we register these initialization functions to. At the beginning of main(), the said registrar object goes through its list of init functions, sorted by relative priority, and invokes them one by one. The static objects can register termination functions as well to be invoked at the termination of main. This way, the relative order is ensured and the initialization and termination are done pre-main (actually, only before all the objects initialized in main(), but after the start of main() itself,) and post-main, respectively.
The problems with this scheme are the verbosity of writing initialization/termination functions, and the fact that the static objects are constructed before main() anyway. We only re-initialize them. This can be costly, wrong or plain impossible, depending on the design of each specific class.
Has anyone got a better way? Any illumination?

VN:F [1.0.8_357]
Rating: 1.0/10 (1 vote cast)

C++
programming

Comments (1)

Permalink

C++: Fun With Precompiled Headers

Those of you who have worked on middle-sized to large projects in C++ (any more than 50000 lines of code) know that build time becomes a rather important factor in the development process. On any typical project, a full build time can very well exceed 10 minutes on a modern machine. Although there are many factors aside from mere line count (for example, heavy use of templates) affecting the exact build time, any amount of time more than a few seconds you spend staring at your monitor waiting for a build to finish is hardly pleasant.

On really large projects, some very drastic measures are taken to mitigate the problem of build times. These may include distributed (even grid-based) build systems or dedicated build machines that automatically build the project after each code update to the project repository or at designated intervals. But for any smallish company or team, such measures may not be applicable. Using Pre-Compiled Headers (or PCH for short) can be an attractive solution.

First let me go over some basic stuff. As you know, a C++ compiler only accepts individual C++ code files as input (called a compiland (like operand!) sometimes.) Your project might easily have a couple of hundred (to a few thousand) source files (not counting the header files) but each must be fed through the compiler to produce an object file individually. The next step would be to run a linker (or alternately a “librarian”) to link those object files together and produce an executable (or a library) file.

We all know that all the “.cpp” (or “.cc” or whatever) files are compiled separately. The obvious result is that the header files that each source file includes must be read and parsed and incorporated into the object file once for each and every source file. This opens up an opportunity for greatly saving on compile time. You see, a typical source code file is usually between 200 to 2000 lines of code itself, but it very often includes tens of thousands of other code in form of included header files. It’s really easy to see for yourself. Just pass your source code file that includes a handful of STL headers to the compiler and tell it only to “preprocess” the code (check your compiler’s documentation.) Look at the resultant file. That’s what the poor compiler receives for each cimpiland.

If you use template classes and functions heavily, the situation becomes even more difficult. Because each template class will be specialized by the compiler for each usage throughout the code. That is, you write a 500-line template class, and use it with 20 different types as template arguments. That’s 10000 lines of code right there, not to mention the fact that the source is now much more complex for the compiler to optimize and generate target code from. Let’s face it, templates are great facilities for generic programming, cleaner design, better performance and general wizardry, but they’re no friend of the compiler’s!

Anyway, suppose that you include <map>, <fstream> and <algorithm> headers (from STL) in almost all of your source code files. Since each file is passed to a separate instance of the compiler, no information is interchanged between the instances and the compiler reads, parses, generates code from and optimizes all the three header files for each source file. This is clearly superfluous. The opportunity I mentioned is right here. If you could somehow do the many steps necessary for processing these files (or at least some of the steps) and store the results and the state of the compiler somewhere (in a file, for example) you wouldn’t have to do that for every source file. You would just read that intermediate state file almost directly into memory and save a lot of time.

This is precisely what using pre-compiled headers is. There are some restrictions however. The headers you want to compile into a PCH file have to be exactly the same and they have to be included in every source file and in exactly the same order. This might mean that some of your source files may include headers that they don’t actually need, but this seldom causes any problem. Also, it is essential that the headers you want to pre-compile be included as exactly the first statements of each source file. Because C++ code (specially preprocessor code) can affect the way other included header files (that are included further in the file) behave, there must not be any code before the inclusion of the headers intended for pre-compilation or that code too, becomes part of the PCH.

One more thing that is necessary is to tell the compiler to stop putting headers into the PCH at some point. This is achieved by putting a “#pragma hdrstop” after all the headers that we intend to be included in the PCH file, and before anything else.

There’s a convenient way to manage all this. We can put all the inclusion statements of all the include files we want to go into the PCH file, along with the pragma directive in a specifically designated header file (let’s call it “PCH.h“) and include this file at the very top of each and every source file (remember: only source files, not other header files.) This ensures that the header files and their order is exactly consistent across all files and removes the need for much duplication of #include statements that might lead to much grief. (As a side note: Don’t Repeat Yourself!)

Now, you tell the compiler to create the PCH, and use it throughout the build. Therefore, you have to change the compile command for exactly one of your source files to create the PCH while it’s being compiled (and put this command at the beginning of the list of files to be compiled in your Makefile or whatever) and change the compile command of all the other source files to only use this newly created PCH file.

Since the precompiled header can become a very big file (many tens or even hundreds of mebi-bytes) and it has to be rebuilt every time either the headers included in it are changed (a genuine requirement) or the source file used to create it changes (imposed, because the code in that file will not be included in the PCH anyway) we can create a dedicated source file just for the purpose of PCH creation. This (e.g.) “PCH.cpp file will be empty except for a single #include <PCH.h> statement. This way, this source file never changes and one cause (however minor) for rebuilding of PCH is eliminated.

For those of you who use IDEs and Microsoft Visual Studio in particular (like myself) here’s how you do it in the VS IDE. First go on and create the said “PCH.h” and “PCH.cpp” files above. Remember to include “PCH.h” in every source file at the very top and remember to add “PCH.cpp” to your project. Also very important is that you must remove all the inclusion statements of the files already included in the PCH from each and every source and header file in your project (it’s best to #define them out (actually #if defined them out,) in case this didn’t work out for you and you wanted them back!

OK. Now you have to tell VS to tell VC that you’re going to use PCH. Go to Project->Properties and in that dialog (while making sure “All Configurations” is selected in the “Configuration” combo box on the top left) Configuration Properties->C/C++->Precompiled Headers. Change the value of “Create/Use Precompiled Header” to “Use…” (with command-line switch of “/Yu”) and change the file name in “Create/Use PCH Through File” to whatever the name of your header is (”PCH.h” in our example) and don’t forget any path prefix it might have (you shouldn’t give an absolute path here, but a path relative to one of your include search path directories or your source file directory.)

This has the effect of setting the compile commands for all your source files to use PCH. But someone has to create it first! Find (in “Solution Explorer” window,) the source file you designated to create the PCH (for example “PCH.cpp”) and (right-click on it and) open it’s “Properties” dialog. While again making sure “All Configurations” is selected (as opposed to just “Debug” or “Release” or whatever), find your way to the same place as before (PCH settings.) These are the build options just for our selected file. Only change the “Create/Use Precompiled Header” to “Create…” (instead of “Use…”) and your all set. You should not change the name of the files (neither the header file nor the resulting PCH file) in this dialog.

Now make a full rebuild of the project. If you’ve done it right, and I haven’t forgotten anything important, and your project is big enough, with this rebuild you should see a great speed up. I have seen build times go from 20-25 minutes to 5 minutes and from 8-9 minutes to 1:50-2 minutes instantly.

I suggest you time your builds before and after the use of PCH (in VS2005, go to Tools, Options…, Projects and Solutions, VC++ Project Settings, Build Timing and set it to “Yes”.)

One thing to note. Sometimes, if your project is large enough, the VC compiler will run out of memory and terminate while building the PCH. In that case, you should append a “/ZmXXX” to all your compile commands, where XXX is the amount of memory in some weird scale and unit. Check the compiler documentation (or follow the build error you get when you run into this problem.) In order to do this inside the IDE, go to you project properties dialog, make sure “All Configurations” is selected, go to “C/C++”, “Command Line” and add the (e.g.) “Zm150″ to the (probably) empty box of “Additional Options”. Experiment with the value a bit to find a suitable value that doesn’t exhaust all your available memory and still allows a build.

I hope this mini-guide comes handy to someone someday! Please let me know of any errors I’ve made, or any omissions or inaccuracies.

VN:F [1.0.8_357]
Rating: 1.0/10 (1 vote cast)

C++
programming

Comments (8)

Permalink

KOPCS Distribution 1371

This is the long overdue package (and “ymeta” file,) containing KOPCS source code (verion 1.0.0 (codenamed Rincewind) build 1371.) The package also contains pre-built binaries mostly for Windows, but “Zero” is provided for 32-bit x86 Linux as well.
The package contains KOPCS (plus less-than-minimal documentation,) JFKOPCS scripts, yCrypto (plus documentation,) Zero, the web page templates, some tests and VS2005 project files and Makefiles.
There’s no guarantee that anything in it works or even compiles. Do not trust anything you hear or receive from me! The only external dependency is MySQL (preferably 4.x or 5.x, but 3.2x may work) to build and run and Apache 2.0.x or 2.2.x to run it.
There’s no setup guide whatsoever. Good luck!
BTW, I’m going to setup a subversion repository for KOPCS soon. The only problem I have is migrating from the existing local CVS (on Mike) to a remote SVN on yaserzt.com.
UPDATE 2007-11-04: The authors of KOPCS are (in no particular order) Ehsan Adeli Mosabbeb, B. Maryam Elahi and myself. The source code has been released with their expressed permission. An implementation of the SHA-256 in JavaScript language by Angel Marin has been used. Please refer to the file “webfiles/media/sha256.js” in the distro for more information.
I guess a quick note about licensing is in order. All the work done for KOPCS by the above-mentioned authors are released under the terms of the Lesser General Public License version 3 (a.k.a. LGPLv3) with the exception of the IAUM-CCC website templates and the JavaScript code used in it, which are under the terms of the General Public License version 3. The website templates include and is limited to any file with the extension of “.htmltemp”, “.js”, “.css”, “.png” and “.ico”. Note that KOPCS is released AS IS in the minuscule hope that it would be useful, but without any guarantee (even implied) that it will be suitable for any purpose. That means, if KOPCS destroyed your hard drives or burned down your house, it’s your fault not ours!

VN:F [1.0.8_357]
Rating: 1.0/10 (1 vote cast)

C++
KOPCS
code
programming

Comments (4)

Permalink

Torvalds’ Folly

Read this message on the subject of C++ as a programming language from Linus Torvalds.
To give you a little context, this is the git mailing list (or rather, newsgroup) which is the revision control system they chose after all the controversy around BitKeeper (which was proprietary and not at all suitable for the Linux kernel.)
Torvalds and others are developing git from ground up and they have opted to use C as opposed to C++. This message here is Torvalds going medieval on some guy because he suggested that they could start using C++ features to make their software better.
He even mentions STL and Boost as samples of bad C++! This is not the first time I’ve seen him act like this (not the opinion, but the behavior) which might be expected from someone who has zero time for newbies, but the opinion. Man, is he wrong! He just doesn’t understand that a language is just as good as the programmer. He seems not to realize the “zero-overhead” rule of the C++ language: that no feature of the language has any runtime overhead when not used.
Anyway, I knew Torvalds was a bad leader (because of his attitude towards free software (as opposed to merely open-source software)) but I still counted him as a brilliant programmer and engineer. I guess we cannot rule out the “engineer” part, because of the evidence in the form of the kernel, but the “programmer” part has become under a dark cloud in my mind.

VN:F [1.0.8_357]
Rating: 1.0/10 (1 vote cast)

programming
rants

Comments (0)

Permalink

C++: Fun With Comments

There’s much fun to be had with C++ comments, and a lot of seriously usable tricks there as well. Of course, most of programmers already know all I could tell about the subject, but nonetheless, I think I’ll take a shot at bringing all the techniques I think might be useful together, and I might be able to use a few possible tricks that a possible visitor would possibly leave on this post!
The first thing any programmer has to realize about comments is that (as their name suggests)

Comments are not the code that the compiler doesn’t see, but the sentences that a human would read.

Write comments (and code in general) for another human (or you yourself) to read. This generally means you should generally avoid too clever constructs that have no other advantage. I say it again: Write code for other humans to read, not the compiler to compile.
You can use special comments and tools like doxygen to generate useful, beautiful, always-up-to-date and comprehensive documentation of your source codes automatically, with little extra work (e.g. with putting a line with three slashes (”///“) at the beginning and describing the purpose of a function before its prototype.) These kinds of tools make you appreciate the value of comments!
My first advice is never use “//” or “/*” to comment out a piece of code. Those characters are reserved for “comments”, i.e for writing descriptions of your code! Always put another character (or sequence of characters) after them, and use different characters to distinguish the different situations in which you’ve commented out the code. For example, use “//0” and “/*0” for code that you suspect is incorrect, use “//1” and “/*1” for test code, and so on and so forth. Keep in mind that these are only suggestions. Any system you opt to use, must be documented somewhere. Write 10 lines to describe the meaning and connotation of the 10 different types of comments you use. Don’t take this lightly! As time goes by and you write more code, you’ll accumulate these rules and split or merge them, but your commenting rules become more comprehensive, more concise and more useful.
Anyway, suppose you want to comment a multi-line piece of code. Always put the comment openning and closing on a line by themselves. No code on those lines! Also, use “//*/” for the closing marker (instead of just “*/“.) This way, you can uncomment and recomment that part with only a single character; a ‘/‘ that you add to or remove from the beginning of the openning marker. Look at snippets 1 and 2.
There are times that you want to switch between commenting two parts of a single line. In these situations, you can put “/**” before the first part, put “/*/” between the two parts and “/**/” after the second part. Like snippets 3 and 4, you can then switch between the first part being commented out and the second one by adding a single ‘/‘ after the comment before the first part. (Also note the parsing/formatting bug of jEdit on line 18!)
You can also do it in the slightly prettier way that snippets 5 and 6 demonstrate (I really think so!) but only if you want to switch between two multi-line segments of code.
Commenting large blocks with “/*” and “*/” has a major problem. The commented blocks don’t nest. For this reason, I suggest the cleaner method of using “#if 0“, “#else” and “#endif” blocks (snippets 7 and 8, but they lack the coloring.) This way, not only you can nest commented out blocks inside of each other and enable/disable them individually just changing the ‘0‘ to ‘1‘ (provided the outer blocks are not disabled) but also you can comment the commented-outness(!) of these peices, and you can use preprocessor macros instead of just ‘0‘ to be able to switch these segments on and off from elsewhere. The only problem is that many editors and IDEs don’t process preprocessor directives and they won’t colorify the disabled parts as inactive.
In your “comment” comments, you can use well-recognized keywords like “NOTE“, “WARNING“, “TODO” and “FIXME” to make their meanings more apparent and to searching for them easier. Just remember to use them neatly and consistently.
If you have more ideas for using comments, I’d be happy to hear about them and to include them here. By the way, anybody has a clean and pretty way of switching (commenting/uncommenting) among three or more segments of code?

   1://{Snippet 1}
   2:/*0
   3:    for (unsigned i = 0; i < v.size(); ++i)
   4:        swap (v[i], v[v.size() - 1 - i]);
   5://*/
   6:
   7://{Snippet 2}
   8://*0
   9:    for (unsigned i = 0; i < v.size(); ++i)
  10:        swap (v[i], v[v.size() - 1 - i]);
  11://*/
  12:
  13://{Snippet 3}
  14:    for (unsigned i = 0; i < /**/ v.size() /*/ v.size() / 2 /**/; ++i)
  15:        swap (v[i], v[v.size() - 1 - i]);
  16:        
  17://{Snippet 4}
  18:    for (unsigned i = 0; i < /** v.size() /*/ v.size() / 2 /**/; ++i)
  19:        swap (v[i], v[v.size() - 1 - i]);
  20:        
  21://{Snippet 5}
  22:/*0
  23:    for (unsigned i = 0; i < v.size(); ++i)
  24:        swap (v[i], v[v.size() - 1 - i]);
  25:/*/
  26:    for (unsigned i = 0; i < v.size() / 2; ++i)
  27:        swap (v[i], v[v.size() - 1 - i]);
  28://*/
  29:        
  30://{Snippet 6}
  31://*0
  32:    for (unsigned i = 0; i < v.size(); ++i)
  33:        swap (v[i], v[v.size() - 1 - i]);
  34:/*/
  35:    for (unsigned i = 0; i < v.size() / 2; ++i)
  36:        swap (v[i], v[v.size() - 1 - i]);
  37://*/
  38:        
  39://{Snippet 7}
  40:#if 0
  41:    for (unsigned i = 0; i < v.size(); ++i)
  42:        swap (v[i], v[v.size() - 1 - i]);
  43:#else
  44:    for (unsigned i = 0; i < v.size() / 2; ++i)
  45:        swap (v[i], v[v.size() - 1 - i]);
  46:#endif
  47:        
  48://{Snippet 8}
  49:#if 1
  50:    for (unsigned i = 0; i < v.size(); ++i)
  51:        swap (v[i], v[v.size() - 1 - i]);
  52:#else
  53:    for (unsigned i = 0; i < v.size() / 2; ++i)
  54:        swap (v[i], v[v.size() - 1 - i]);
  55:#endif

UPDATE:I was wrong about the parsing/formatting bug in jEdit I mentioned above. That’s a Doxygen comment and jEdit handles it correctly. Oops!

VN:F [1.0.8_357]
Rating: 1.0/10 (1 vote cast)

C++
code
programming

Comments (0)

Permalink

A Breach in the Hull

The Convex Hull code I posted earlier on this blog has a bug. When the points are all have the same X component, the implementation will misbehave. I may post a fix later; I’m off to work now, but I had meant to write and mention this for so long that when I remembered the matter in the shower I didn’t postpone the writing in fear of forgetting it once more.

VN:F [1.0.8_357]
Rating: 1.0/10 (1 vote cast)

code
programming

Comments (0)

Permalink