C Programming Language: shorthand

If you’re writing a lot of code you want to use as few keystrokes as possible. After all, aliments like tendonitis and carpal tunnel syndrome are career threatening for professional programmers. That’s way many languages have shorthand syntax to save time and keystrokes. The C language is no different, and I’ll share this quick tip about it after the break.

Shorthand in C is extremely simple. Any time you are assigning a value of a variable that uses that variable in the assignment you can simplify the syntax. For example:

myVar = myVar + 32;

This line of code adds 32 to the current value of ‘myVar’. But you don’t need to type ‘myVar’ twice. Instead, move the operator (that’s the plus sign in this case) to the left side of the assignment operator (the equals sign). The portion of code originally on right side of the operator will be the only thing still remaining on the right side of the assignment operator in our shortened code snippet:

myVar += 32;

This will work for any type of operator, and for any complexity of assignment as long as you can get the variable alone on the left side of the argument.

If you want to use a bitwise operator on a variable:

myVar = myVar & 0xFF; //Traditional
myVar &= 0xFF; //Shorthand

It can be used by the shifting operators as well:

myVar = myVar << 1; //Traditional
myVar <<= 1; //Shorthand

Conclusion

If you weren’t already familiar with this, it should make it much easier to read other developers’ code since shorthand is almost always used when it can be. It will also increase your coding speed, and decrease you hand and wrist pain!

Leave a Reply