Back to C++

September 10, 2008

It has been a while since I have had the time to sit down and write something here so I figured now is as good a time as any. I actually have class in a bit, but I figured I would be able to get something down of mild interest before I leave.

As one of my final computer science classes before I graduate I am taking a class based largely in theory. Mainly we will be studying NP-Complete problems, but we will study some other topics as well, which I may blog about when the time arrives. Until a few days ago we did not actually have any homework assignments which involved programming 😦 .

The assignment we did get, though, was pretty interesting. The basic idea behind it is that you must take the string 123456789 and insert +’s, -‘s, or nothing in between digits. Also, for our class, you could also place a – or + sign in front as well (though the + doesn’t really do anything) . You must generate all possible combinations of this string and find the smallest possible positive integer that you can create in this way. This required us to implement an algorithm (which we learned in class) that can be used to generate all possible combinations of some arbitrary set (i.e. the power set). We were allowed to write this program in any language of our choosing. I joked around saying I would try and write it in MIPS assembly or LISP. I did seriously consider LISP, but I lacked the ambition to relearn it. In the end I decided to write this in C++.

My design of the problem wasn’t anything noteworthy, and that is not really the point of my writing this post. I simply really enjoyed writing C++ code again. It took me a little bit to get back in to the spirit of things, but once I remembered the little syntax quirks and general coding style I was loving every minute of it. This program did not take all that much time to program, nor was it particularly challenging. Perhaps I just have a sentimental feelings for C++ as it was always a language I had aspired to learn since I started programming in the 8th grade. I was extremely pleased that my college offered it as a course. Sadly, the intro level classes are now taught in Python, which I have mixed feelings about. I’m not sure if a language will come along that I will ever like more than C++, but who knows what is on the horizon.

C++ just seems to be the best combination of two worlds of programming that I enjoy. The low level access to memory, variables, other reasources of C, and with support for OO style programming. I know some would argue those should never be combined. For me I just like knowing that if I need to access the low level stuff it is readily available, and that I do not have to jump through hoops to use it. With an OO language I know that you are typically trying to write high level code, and I would say that is true for me most of the time. However, access to pointers can really come in handy in certain circumstances. Yes, I know there are workarounds for other languages, but it is convient to have them right at your finger tips.

Perhaps I am just holding on to my past, but I sure do enjoy coding in C++ 🙂 .


Is C++ an Elitist Language?

August 9, 2008

Recently I made a post about some things in Java that I find to be a bit of an issue. The artcle was reposted on Javalobby and it started an interesting discussion in the comments section. Among other things, one comment in particular struck me as disconcerting:

When you use a language you should ask yourself what is the feeling of it. C++ is an elitist language with strong roots in the procedural C (that should compile in C++), and a big focus on performance. Java  is a full Object Oriented langage inspired mainly by C++ and smalltalk, which was for a long time pretty slow, and focus on writing big maintainable programs via simplicity and strong typing. ( A comment by Raphael_Lemaire @ )

Specifically the part about C++ being elitist. Now, I love C++, so of course I am biased. However, I never thought of it as being elitist. The funny thing is that the syntax of C++ is very close to that of Java, does that mean Java is elitist? As far as I see it the real difference is that Java: offers you loads of libraries, memory management, and it allows the coder to not have to think about pointers. Lets look at each of these issues.

The first issue, of libraries, I don’t really consider much of an issue. Especially if you use open source libraries there are hundreds of libraries which are readily available. Certainly the Java libraries are nice, and most, if not all, are guaranteed to be cross platform. However, many of the C++ ones are as well so I also consider that argument to be a moot point. The fact that you have to compile them for each  different platform can be a problem at times, but I consider it a minor problem especially given the speed of modern computers.

The second issue of memory management is something that goes to Java’s favor. I think, however, that it is a minor issue in the scheme of things. Once you understand the basic idea of memory management, and as long as you use a good programming style which favors allocating and freeing memory in the same place, this isn’t as big of a deal. I have written that you can leak memory in Java too, so Java is not free of this nuisance either! Therefore Java coders who think that are impervious to problems with memory are just kidding themselves.

Third is the fact that in Java you don’t deal with pointers. Or, rather, you don’t have to think about them even though you deal with them all the time. This is more personal opinion than anything, but I never found pointers to be that difficult of a thing to deal with. Once you get an understanding of them it’s really a trivial matter. I know that some people make a fuss because you have to always be thinking ‘is this a pointer to an object, or the object’, but that consideration has never slowed me down. You make note of it once and then it stays the same throughout.

So what is it about C++ that makes it elitist? Is it the people that write code so convoluted that only an experienced pro can read it? I think this could be a big part of it. No matter what language you use people can always write unnecessarily confusing code. Languages like Java try to help prevent this, but I’m sure it can still be done. Having access to pointers can lead to code that is difficult to read, but I think the problem there has more to do with the coders than the language. Programmers should be wise enough to write readable code, and not blame the language.

Do you blame English when you can’t spell a word? I mean… silent letters, what is up with that? No, you probably blame yourself for not having put in enough time to learn the proper spelling. So why should we blame C++ for people that write obfuscated code? At the end of the day it all comes down to the coder, and whether they want to write good code or not.

The bottom line is that I don’t consider C++ an elitist language,  but rather a language that with some extra consideration can be just as easy to code in as Java.

Java and Memory — Yes, it Can Leak

July 29, 2008

Note: I had previously posted this on my SourceForge Diary on 6-18-08 , but after two posts to the diary I decided the blog was a better place :).

I have been keeping up work on Spheriosity lately as I have devoted my summer to it. Normally I spent around 7 or 8 hours a day writing code for it. Then on the weekend I try to give myself a bit of a break from staring at the computer screen 😉

Before I get in to the main point of this entry I will just list a few things I have done with Spheriosity recently:

  • Added the ability to place a point on a line
  • Moved the move point button to the draw section
  • Wrote unit tests for the new code (putting a point on a line)
  • Added a little information section to the bottom of the window which displays area, radius, etc.  so the user has some idea what is going on

There are other small changes and if you really want you can investigate the CVS logs. When I release the next version (hopefully the end of the month) I will introduce a changelog file where I will try to sum up all the new features! As a simple FYI the next feature I plan to work on is parallel transport 🙂  I can’t wait to get this implemented, but I do not think this will be any trivial task so please be patient with me as I work on this.

Anyway the reason I started this journal entry was because I just found a huge memory leak today in Spheriosity. A memory leak!? In Java!? YES! You CAN have memory leaks in Java. This realization hit me pretty hard today when I found out that I was wasting a lot of memory. Before today I had let the lore of Java convince me it was impossible to have memory leaks, but it’s true… you CAN have them.

How is this possible you ask? Well it has to do with how garbage collection works. Yes, in the traditional sense of C/C++ you can not have a memory leak where you personally forget to deallocate a chuck of memory. This still does not explain what I mean by memory leak though. I am talking about what happens when you hold on to a reference of an object long after it is needed. This happens very easily with private class variables and static variables. Lets talk a bit about garbage collection:

(This is simplified and I am sure the Java garbage collector is far from trivial, but I will simply explain what I know) In a nut shell the garbage collector knows it’s time to get rid of an object when there are no more references to it in code. So if you are storing an object in a private class variable and no longer need it you should set that variable to null. Especially if the class is going to be around for most of the life of the program. This is quite plausible with things such as user interfaces. It is also worth mentioning that you can think of this as a tree like structure. If you stop referencing a class at the top of the tree the entire branch will be collected as long as the only references to the sub objects occur within that branch.

In Spheriosity the problem I had was that after a user selected ‘New’ to clear the sphere I simply removed the highest node in the scene graph from the scene graph and did not clear all of the objects out of it. This caused everything in the frontend and backend to be kept around! All it took was a single line to clear out the scene graph. There were issues where I would get rid of some frontend objects but it was still an observer to something in the backend. As such the garbage collector would never collect it.

Now that I have learned all of this I will be extremely careful to avoid any future memory leaks. I am also going to be more careful when I explain memory management in java to people. I hear people say all the time that it is so amazing and they make it sound completely fail proof, but that is NOT the truth. You still need to be careful with how you manage memory. There is an entirely separate issue here known as heap smashing and in short it is caused by calling ‘new’ too much and forcing the garbage collector to work overtime! This is a conversation for another day, however.

I hope that I have enlightened at least one person about some of the pitfalls of Java. I still like the language and the library support is awesome. However I will never again say the memory management is easier than C++. The reality is that you have to be just as careful! Why do I care so much about memory usage? Well, I don’t like programs that are memory hogs so I try to create ones that don’t hog memory in their own right.

Sometimes I start to think Java itself is a memory hog by default because of the virtual machine and I do get concerned about that. However, without Java3D Spheriosity wouldn’t be anything that amazing so for now I will be sticking with Java 🙂

PS: The cross platform support is nice too 😀

The Importance of White Space in Code

July 18, 2008

For almost as long as I have been writing code I have tried my best to improve upon my coding style. This is, of course, an area of much controversy among computer scientists. What makes “good” style? Sometimes its purely a matter of opinion. What I find easy to read might not be so easy for someone else. I suppose this is one reason you might argue that programmers should all try and adhere to similar styles. This way any code would be just as readable to anyone.

Almost every language I have ever used allows you to put in more white space than you need, and anywhere you want to. I find this to be quite a useful feature. Not because I think it allows me to write better algorithms, but because it helps me organize the code and suggest certain things to the reader. To some degree making readable code is very much an art [one that I do not claim to have mastered]. I think adding white space in blocks of code to segment it into different sections is good practice. Lets take the following C code for example. Keep in mind that this could be any language and the same concepts apply:

#include <stdio.h>
#include <stdlib.h>
int main(int argv,char** argc)
  int x;
  int y;
  int sum;
      printf("Random number is %d\n",sum);
      printf("yay for loops\n");

Now, I will be the first to admit that this code is fairly random and doesn’t do anything of extreme usefulness, but that is not the point here. Notice this same program with a little extra white space added:

#include <stdio.h>
#include <stdlib.h>

int main(int argv, char** argc)
  int x;
  int y;
  int sum;

  for(x = 0 ; x < 10; x++)
    for(y = 0; y < 10; y++)
      sum = x+y;
      sum = sum + x*x + y*y;

      printf("Random number is %d\n", sum);
      printf("yay for loops\n");


To me, this now really pops out at you, and it is much easier to see the different “areas” of this code. You have the #includes which are separated from main. This lets you know when the real code begins and puts a break between the includes and the actual code. It suggests a change in context! The next place I added white space was between the arguments in the header to main. This allows the variables (argc and argv) to stick out more to the eye.

In the actual function I put a space after I declared all the variables. Again, I use the idea that with the return we will have a change of context going from variable definitions to more concrete code. In each for loop I separated the different parts of the loop constraints to make them a tad easier to read.

Within in the inner for loop I added the most space. First I separated the mathematical statements from the print statements. You may not always want to do this because sometimes you might group a print statement for a specific calculation with the rest of the calculation, it all depends on what you are trying to say. Next I separated the different parts of the second equation to bring out the more
interesting parts. Sometimes I will add parenthesis to really be explicit as to what I am trying to do, but this didn’t see to warrant that.

Finally at the end I separated the exit(0) from the end of the for loops because it is not really part of that block of code.

So there you have it. This is a bit of a trivial example, but I think it shows that a little white space can go a long way in bringing things out to a foreign reader. Remember, the new person who reads your code will be looking for any hints they can get as to its functionality. When you are writing the code you may not need the white space to understand what is going on. However, 6 months later it
could even help you figure out what was originally intended as well as the newcomer to the code base! There’s plenty of other tricks to help make code more readable: descriptive variables, good function names, good functional decomposition, etc. I just wanted to point out one area that I think can be easily overlooked 🙂