Never ceases to amaze how that Mike Ash fellow keeps teaching us new stuff about the basic C language. The latest is
Friday Q&A 2011-02-18: Compound Literals
This time we were sure there wouldn’t be anything new to us, we use compound literals for field initialization every time we create a struct pretty much … and wrong again!
Specifically, did you know that compound literals are mutable?? We did not know that compound literals are mutable
One really unintuitive thing about compound literals is that, unless you declare their type as const, they produce mutable values. The following is perfectly legal, albeit completely pointless, code:
(int){ 0 } = 42;
Less uselessly, this fact means that you can take the address of compound literals, and it’s safe to pass them to code which will modify the pointed-to value…
A fairly trivial syntactic convenience in most cases, but there is one instance where it can make your code significantly more clear and robust, and that’s when writing functions with optional parameters; things taking NSError ** for example. Which you typically write with if (*error) every few lines … unless you forget to do so until it crashes … or you keep auxiliary errors, or something tedious, anyways. Taking this mutability into account, you’d write something like
- (BOOL)doWithError: (NSError **)error
{
if(!error)
error = &(NSError *){ nil };
if(fail1)
{
*error = [NSError ...];
return NO;
}
if(fail2)
{
*error = [NSError ...];
return NO;
}
return YES;
}
Well, that’s rather more straightforward and robust, isn’t it? Yes, we will definitely adopt that style from now on.
Lots of other good tips and discussion in the article and comments, so read all the way to the end!
Continue Reading →
20
FEB
Share