January 16, 2005

First Post, Kinda and ++/-- Thoughts

This is my first post from my new apartment in Dallas, Texas.

Getting to this point was a challenge to say the least. Between Circuit City ending up delivering over a week late, components popping out of place in my Media Center PC and massive dents in my case thanks to UPS thinking that "Fragile" means "Beat The Living Shit Out Of It," and Comcast freaking out because it took me over a week to activate my broadband modem, it's been fun.

The Ritual crew has been amazing to say the least. They've gone out of their way to make me feel welcome in my new home state, especially since my wife won't be down here for a little over two more weeks. I've been trying to get my head wrapped around C++ again, and I've remembered why I hate the ++ and -- operators.

For those who are not aware, the ++ and -- operators either add or subtract one from a variable. If the ++ goes before the variable, it adds one prior to the value being used, and adds one after the variable is used if the operator is placed after the variable. That's fine if you only have one on a line of source code, but what if you have multiples that rely on each other? That's a recipe for disaster as the order the instructions are handled is not specified in the standard.

Let's say you've got an app like this:

//NOTE: Stunt code.  I'd never ship code like this.

int f(int a, int b, int c)
{
return c / (b / a);
}

int main()
{
int a;
a = 1;
return f(a++,a++,a++);
}

You want this code to be portable across platforms and across compilers, and you want the results to be consistent. For this discussion, I'm going to focus on the last line of main(), return f(a++,a++,a++);.

Let's say that your compiler handles the operators going from left to right. In that case, the compiler will pass in the values (1,2,3). However, several handle the operators from right to left, so those compilers will pass (3,2,1).

Now let's say that you have an aggressive inliner. Because we're using the operators in reverse order in the function, and because of the grouping in the function, some will pass in (3,1,2). You may say that the compiler is broken, but the compiler is merely following the standard, which does not specify what order they should be processed?

Fact of the matter is that ++ and -- are excellent shortcuts, but should never have multiples used in a single line of code, especially if the variables depend on each other's values. That would be bad, mmm-kay?

No comments: