This week a colleague sent me a snippet of Objective-C syntax I had never seen before.
This is (apparently) called C99 Initializer Syntax. This type of syntax can be used to initialize any struct in C (and Objective C) which is especially useful when working with CGRect and CGPoint.
Let’s take a look at the standard way of defining a CGRect.
I’ve never really thought about this, but the syntax only makes sense if you already know the order of the parameters and what they mean. This is not really an issue with CGRectMake – since you use this so often it’s impossible not to know the parameters – but it’s not ideal.
Take a look at the equivalent in C99 syntax.
This is much more readable and would be especially helpful if you were passing expressions instead of contants.
What’s really nice about this syntax is that it’s not only more readable, it’s actually a bit safer. We can also write the following:
We can also change the order of the parameters in the original struct without having to change this code. Obviously I’m not expecting the definition of CGRect to change, but it could be useful for your own structs or those of a library. (Remember that this syntax works for all structs)
The best usage of this syntax (in my opinion) is for when we want to specify the size or origin as a single value. For example, it’s not uncommon to do something like this:
However, with the C99 syntax we can now write this:
Which is definitely much more readable.
Any parameters which are not specified will default to zero. So the following statements are actually equivalent.
Using this syntax we can actually rewrite the original snippet I was looking at:
C99 Syntax can definitely be helpful in the right situation. Used correctly it can improve readability, used incorrectly it can make your code overly verbose.