Hate UML?

Draw sequence diagrams in seconds.

Coding tips they don't teach you in school
Posted on: 2009-06-23 09:45:19

Here are some C coding tips, because I have been unable to post anything for a while.

Some of these time-saving shortcuts are intended for small projects or prototyping code.

The nested ? : trick

The switch statement is very efficient, and the compiler will often implement it as a table lookup so it doesn't have to do any comparisons. But it sure can tire your fingers in a hurry:
switch( number ) {

    case 1: str = "one"; break;
    case 2: str = "two"; break;
    case 3: str = "three"; break;
    case 4: str = "four"; break;
    case 5: str = "five"; break;
    default: str = "unknown number"; break;

If getting the code out is more important than its speed, you can use a nested conditional operator to save typing:

str = number == 1 ? "one" : 
      number == 2 ? "two" :
      number == 3 ? "three" :
      number == 4 || rand() == 42 ? "four" :
      number == 5 ? "five" :
      "unknown number";

You can freak out your coworkers if you do it all on one line.

DeMorgan's theorem of negativity

// if blah blah blah blah blah blah....
if ( !(A && B) )

is the same as

// if blah blah
if ( !A || !B )

Pick the one that is easier to understand and read out loud. It is usually the second.

Rounding numbers using integer math

Suppose you have 2001 boolean variables, so you want to keep them in a bitmap of bytes, 8 at a time. How do you declare this array?

#define NUMBER_OF_BITS 2001
unsigned char bitmap[ NUMBER_OF_BITS / 8 ]; // FAIL!

The computer uses integer math, so 2001 / 8 is 250 and there is one bit left over. When you store bit 2001, you will corrupt memory. You can round numbers up like this:

unsigned char bitmap[ (NUMBER_OF_BITS + 7) / 8 ];

This works because integer division always rounds down. However, if you add the divisor less one, then you will force it to always round up. It will also work for 32 bit integers:

unsigned int bitmap[ (NUMBER_OF_BITS + 31) / 32 ];

Real rounding via integer division

Adding something before dividing is a general technique. This code rounds a and b to the nearest 10.
int a = 12;
int b = 16;

printf("Round a: %d", (a + 5) / 10 * 10 );
printf("Round b: %d", (b + 5) / 10 * 10 );

Multiply by arbitrary numbers using shift

Sometimes, for good reasons, you need to hand optimize your code. But most of the time, somebody is just showing off, and you will see code like this:

b = ( a << 1 );

This is the same as multiplying by 2. Because of the way binary numbers are represented, you can multiply by any power of two by shifting by that power. You can also multiply by other numbers.

// b = 10*a, which is 8*a + 2*a
b = ( a << 3 ) + ( a << 1 );

Division isn't as nice looking.

Getting array sizes

In C, you can get the total size of an array in bytes using the sizeof operator. Dividing it by the size of each element will give you the number of elements in the array.
MyHugeStructure array[100];
int i;

for( i = 0; i < sizeof(array)/sizeof(*array); i++ ) 
    array[i].id = i;
The downside is that if you ever change the array to be dynamically allocated using new or malloc(), then sizeof() will only return the pointer size. Of course, in a large project you should have have a defined constant for the number of entries.

Else Flattening

Deeply nested else clauses are hard to understand. But if they look like this, you are in luck:

if ( A ) {

} else {
   if ( B ) {

   } else {
       if ( C ) {


Save money on wide screen monitors by flattening the elses.

if ( A ) {

} else if ( B ) {

} else if ( C ) {


Black is White and Up is Down if you're not using a mainstream compiler

If your code has to run on a lot of different platforms, you should know that GCC and Microsoft VC++ are very similar and this similarity will trick you into thinking that all compilers are alike. But the C standard leaves a lot of stuff out that will surprise you, if you do work on embedded systems with crappy, but standards-conforming compilers.

What is sizeof(char)? In most compilers it is 1 byte. Switch compilers, and it might be 2 or 4 bytes. The C standards only says that it cannot be larger than an int.

What happens if you add something to the maximum integer?

int a = MAX_INT;
printf("%dn", a);

In mainstream compilers you get a negative number, since the number space wraps around. But the C standard says the result is undefined. So some compilers will leave a at the maximum value, MAX_INT.

And don't even think about bit-shifting a negative number:

int a = -2;
printf("%dn", a >> 1 );

Want more programming tech talk?
Add to Circles on Google Plus
Subscribe to posts

Post comment

Real Name:
Your Email (Not displayed):

Text only. No HTML. If you write "http:" your message will be ignored.
Choose an edit password if you want to be able to edit or delete your comment later.
Editing Password (Optional):

Real Name

2009-06-24 01:09:22

matt burns

2009-06-24 07:18:08
Understanding a bit of logic was essential for me recently when I worked with an in-house programming language from the 70s that didn't allow parentheses.

Modus ponendo tollens.


2009-06-24 07:47:00
Multiplying by shifting is done for you by the optimizer if it makes sense. Don't bother doing it in your own code.


2009-06-24 14:37:39
By default, I would suggest anyone asking to do multiplication by bitshift offer concrete proof that the compiler isn't doing it already, and that it's safe.

Jakub Kaplan (jk451)

2009-07-04 14:01:29
Note that there is a rather serious nice use for bit shifting.

Assuming you are in an environment where saving memory is more precious than saving time, you can do so by "packing" information into casual numbers.

E.g. you've got 32 boolean flags determining settings of your program. Then you can save 1 to 5-th flag by doing:


Extracting is analogous.

David Kerkeslager

2009-07-18 00:23:05
Adding to the else-if flattening tip: you can make your indentation more consistent by using a if-elif*-else? structure (* and ? used in their regular expression sense). This can be accomplished in C/C++ using a simple macro:

#define elif else if

OK Programmer

2009-07-18 01:14:26
The nested conditional type is a terrible idea in this circumstance. Instead of letting the compiler generate a O(0) table, you let it generate a O(n) set of if statements. For the non-algorithmic people out there, this means the table lookup always take the same amount of time (and will be much faster than the ifs here), whereas the nested conditionals will keeping checking deeper executed until a match is made.

David Kerkeslager

2009-07-18 01:16:16
Jakub, this will be faster and will work on more compilers. flags should be an unsigned int to avoid twos-complement storage (let's assume 32 bits, so bits will be numbered 0-31).

// Set the xth bit (to 1).

flags |= 1 << x;

// Clear the xth bit (set it to 0).

flags &= ~(1 << x);

// Flip the xth bit (if it's set, clear it; if it's clear, set it).

flags ^= 1 << x;

// Extract the xth bit as an integer and store it in test.

test = flags >> x & 1;

Dan D.

2009-07-30 17:35:16
This list is... just not very good. Parts of it are plain wrong, and others are not as advertised.

On the ternary conditional operator ?: : yes it saves on typing but it's dog-slow compared to a switch statement. Save it for when a switch statement won't work (for instance, when an expression must be reevaluated if it doesn't match). The example you gave is the perfect time to use a switch statement, although your default case should be "str = rand() == 42?"four":"unknown number";break; to make the nested ?: code.

On DeMorgan's: This is CompSci 101, or 201 at the latest. They teach you precisely this in school.

On rounding: this code is not portable to platforms where a sizeof(char) is not 8. For chars the code should be unsigned char bitmap [NUMBER_OF_BITS + sizeof(char)-1/sizeof(char)]; You should be able to figure out how to do that with ints as well.

On real rounding: The best one of the list.

On bit-shifting: if they don't teach you this in school, you're at the wrong school. Same if they don't tell you that if you want multiplication, unless you have hardware reasons to bit-shift (side-effects in a MIPS processor, for instance), you should simply multiply. Let the complier sort it out. The compiler knows better than you, for instance, that multiplication always works, but weird things can happen on certain models of 64-bit processors running in 32-bit mode if you shift left by 32.

Else flattening: seriously dude, what crappy school did you go to that they didn't tell you about this?

On non-mainstream compilers: indeed, so apply that to your own examples! And bit-shifting a negative number works exactly as well as bit shifting a positive number, which is to say, again, if you want multiplication (or division), JUST DO IT!

Sachin Pujari

2009-09-13 07:28:56
You are no big programmer than me, Steve u r just a theif stealing some other authors tips and tricks...


2009-10-21 19:22:48
I'd like to see another one of these what you didnt learn in school articles. hint


2010-01-10 00:28:03
> What is sizeof(char)? In most compilers it is 1 byte. Switch compilers, and it might be 2 or 4 bytes. The C standards only says that it cannot be larger than an int.

No, sorry, that is wrong. sizeof(char) is always 1, and the sizeof all other types is measured in chars. Even if a character is stored as 2 or 4 bytes on some platform, sizeof(char) will equal 1. And don't forget that a "byte" is not 8 bits on every architecture.

John From

2010-01-10 02:24:23


2010-04-10 09:57:43
That is very interrsting in embedded systems


2011-08-08 10:55:22
@Jakub Kaplan (jk451)

rather serious not nice Danger: your flags carry into the next flag if it is set twice. |= would probably be better, (or perhaps a language that doesn't use smileys <= ?:) (or perhaps less than a million settings ;)



2011-08-08 11:01:58
Ok, OK programmer,

branch prediction: but the lookup table is then mispredicted all the time, whereas the nested ifs are correctly branch predicted ~always and therefore free.

this blog is awesome :) all mediocre programmers should advertise themsleves widely so they, and their followers can be screened.


2012-02-03 08:02:29
"What is sizeof(char)? In most compilers it is 1 byte. Switch compilers, and it might be 2 or 4 bytes. The C standards only says that it cannot be larger than an int."

This is wrong. On all compilers sizeof(char) is 1. The C standard defines sizeof in terms of numbers of chars, since a char is one byte. If sizeof(char) is not 1, you're not using a conforming C compiler.

Alex Ratushnyak

2012-05-17 01:17:44
Hi Steve!

If you are a C expert, please try this challenge:

http //www.linkedin.com/groups?gid=4264441


Other posts by Steve

Yes, You Absolutely Might Possibly Need an EIN to Sell Software to the US How Asana Breaks the Rules About Per-Seat Pricing 5 Ways PowToon Made Me Want to Buy Their Software How I run my business selling software to Americans 0, 1, Many, a Zillion Give your Commodore 64 new life with an SD card reader 20 lines of code that will beat A/B testing every time [comic] Appreciation of xkcd comics vs. technical ability VP trees: A data structure for finding stuff fast Why you should go to the Business of Software Conference Next Year Four ways of handling asynchronous operations in node.js Type-checked CoffeeScript with jzbuild Zero load time file formats Finding the top K items in a list efficiently An instant rhyming dictionary for any web site Succinct Data Structures: Cramming 80,000 words into a Javascript file. Throw away the keys: Easy, Minimal Perfect Hashing Why don't web browsers do this? Fun with Colour Difference Compressing dictionaries with a DAWG Fast and Easy Levenshtein distance using a Trie The Curious Complexity of Being Turned On Cross-domain communication the HTML5 way Five essential steps to prepare for your next programming interview Minimal usable Ubuntu with one command Finding awesome developers in programming interviews Compress your JSON with automatic type extraction JZBUILD - An Easy Javascript Build System Pssst! Want to stream your videos to your iPod? "This is stupid. Your program doesn't work," my wife told me The simple and obvious way to walk through a graph Asking users for steps to reproduce bugs, and other dumb ideas Creating portable binaries on Linux Bending over: How to sell your software to large companies Regular Expression Matching can be Ugly and Slow C++: A language for next generation web apps qb.js: An implementation of QBASIC in Javascript Zwibbler: A simple drawing program using Javascript and Canvas You don't need a project/solution to use the VC++ debugger Boring Date (comic) barcamp (comic) How IE <canvas> tag emulation works I didn't know you could mix and match (comic) Sign here (comic) It's a dirty job... (comic) The PenIsland Problem: Text-to-speech for domain names Pitching to VCs #2 (comic) Building a better rhyming dictionary Does Android team with eccentric geeks? (comic) Comment spam defeated at last Pitching to VCs (comic) How QBASIC almost got me killed Blame the extensions (comic) How to run a linux based home web server Microsoft's generosity knows no end for a year (comic) Using the Acer Aspire One as a web server When programmers design web sites (comic) Finding great ideas for your startup Game Theory, Salary Negotiation, and Programmers Coding tips they don't teach you in school When a reporter mangles your elevator pitch Test Driven Development without Tears Drawing Graphs with Physics Free up disk space in Ubuntu Keeping Abreast of Pornographic Research in Computer Science Exploiting perceptual colour difference for edge detection Experiment: Deleting a post from the Internet Is 2009 the year of Linux malware? Email Etiquette How a programmer reads your resume (comic) How wide should you make your web page? Usability Nightmare: Xfce Settings Manager cairo blur image surface Automatically remove wordiness from your writing Why Perforce is more scalable than Git Optimizing Ubuntu to run from a USB key or SD card UMA Questions Answered Make Windows XP look like Ubuntu, with Spinning Cube Effect See sound without drugs Standby Preventer Stock Picking using Python Spoke.com scam Stackoverflow.com Copy a cairo surface to the windows clipboard Simulating freehand drawing with Cairo Free, Raw Stock Data Installing Ubuntu on the Via Artigo Why are all my lines fuzzy in cairo? A simple command line calculator Tool for Creating UML Sequence Diagrams Exploring sound with Wavelets UMA and free long distance UMA's dirty secrets Installing the Latest Debian on an Ancient Laptop Dissecting Adsense HTML/ Javascript/ CSS Pretty Printer Web Comic Aggregator Experiments in making money online How much cash do celebrities make? Draw waveforms and hear them Cell Phones on Airplanes Detecting C++ memory leaks What does your phone number spell? A Rhyming Engine Rules for Effective C++ Cell Phone Secrets