C Code Connundrum

if (tokenOffset + 1 >= MAX_TOKEN_LENGTH)

I’m writing some text decoding stuff at the moment. The piece of code above is a bit of C that I’ve written to make sure than I don’t write over the end of my token array. If the tokenOffset gets larger then the length of the array the condition is true and I will stop writing into it. One of the joys of C is that you have to worry about this kind of thing, otherwise you can overwrite memory and have all kinds of bad things happen. However, the code above is not as efficient as it might be. Any ideas why?

…sound of crickets….

Well, every time the code runs it will have to work out tokenOffset+1, because tokenOffset is a variable. However, look what happens if I do this:

if (tokenOffset >= MAX_TOKEN_LENGTH-1)

The logic is the same, but now I’m subtracting the value 1 from MAX_TOKEN_LENGTH, which is a constant containing the length of the buffer. Since this is fixed at compile time the compiler will just drop the reduced value into the code, so the program now performs no calculations when the test is made. This is the kind of thing that you used to have to fret about, back in the day when every processor cycle was precious. Such fun.

Incidentally, you might be wondering why I have one less character in my text buffer than I think. This is because in C a character string array contains a null character (a character with the code of 0) which marks the end of the string. This character has the lovely name of “terminator”. This does mean that a 50 character array can only actually hold 49 characters, because the last one is the terminator. Another way to solve this problem is to make the array one bigger when you create it, to leave room for Arnold.