Me vs. C: Why int *x and not int* x

[TL;DR   int* i, j doesn’t do what you think it does.  int *i, *j is what you are looking for (assuming you are not a Stormtrooper; in which case, you are looking for droids).]

I was playing with pointer variables (something that I’m still getting used to), and I kept getting confused with a simple inconsistency I kept observing across all C code examples:

Some authors wrote code declaring their pointers as:        int* i;
Other authors wrote code declaring their pointers as:        int *i;

This, you might think, is trivial.  But when developing thousands of lines of code, consistency is important.  Consider a real life example: you go to work every day and observe your co-worker have one cup of coffee with whole grain toast at 9:00AM.  This happens every day.  You can almost set your watch to it.  One day, your co-worker comes in to the office, and doesn’t have coffee.  Cognitive science indicates that you will ask yourself: “What happened?  What’s so special about today?  Is something wrong?  Are we getting laid off?”  The same is true for code; if you start using one style, and switch to another, people will wonder whether or not there is a significance behind the change.  It’s human nature.  So, in a quest to fight this inconsistency (and to cater to my O.C.D.), I went hunting for an answer and was surprised by what I found.

Consider the following statement and hypothesize (no cheating!) what it means:

int* i, j, k;

If you paid attention in your programming class and have used this variable declaration style, your gut reaction (assuming you have not seen this before) is to read this as:  “Declare three int pointer variables: i, j, and k”.

Sorry, wrong answer.  Don’t worry though, I did the same and I won’t allow you to be burned twice.  What the above statement is doing should be read as:  “Declare three variables, a pointer to an int i, and int’s j and k”.

The * binds to a variable, not to a data type.  Which makes sense from a language implementation stand point, because if not you would have to create a data type for each pointer type, and that’s not necessarily good.  (I do not know if this is the real reason why it’s like this, but it’s interesting to think about.  If anyone knows the true reason why, feel free to tell me.)

Oh, C.  Thou art a heartless wench.