Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I was getting tired of repeating types when writing things like this:

NSDictionary* d = @{@"so": [NSNumber numberWithInt:index]),
                    @"much": [NSNumber numberWithBool:accepted]),
                    @"repeat": [NSNumber numberWithDouble:height]};

So I defined a generic macro (a new feature in C11):

#define box(X) _Generic((X), \
char: boxChar, \
unsigned char: boxUnsignedChar, \
short: boxShort, \
unsigned short: boxUnsignedShort, \
int: boxInt, \
unsigned int: boxUnsignedInt, \
long: boxLong, \
unsigned long: boxUnsignedLong, \
long long: boxLongLong, \
unsigned long long: boxUnsignedLongLong, \
float: boxFloat, \
double: boxDouble, \
BOOL: boxBool \

... implement type-specific box methods as well ...

So that I could write things like this:

NSDictionary* d = @{@"so": box(index),
                    @"much": box(accepted),
                    @"shorter": box(height)};

Is this a good idea? Can I expect others to be able to build the code? Will they hate it for not being standard?

share|improve this question
any reason you don't like @(index)? – Bryan Chen Nov 29 '13 at 1:34
@BryanChen I love it! I didn't know about it until you mentioned it just now. Question answered! – Craig Gidney Nov 29 '13 at 1:55
up vote 3 down vote accepted

What you are doing is already provided by Objective-C called Boxed Expressions

with example taken from llvm website

// numbers.
NSNumber *smallestInt = @(-INT_MAX - 1);  // [NSNumber numberWithInt:(-INT_MAX - 1)]
NSNumber *piOverTwo = @(M_PI / 2);        // [NSNumber numberWithDouble:(M_PI / 2)]

// enumerated types.
typedef enum { Red, Green, Blue } Color;
NSNumber *favoriteColor = @(Green);       // [NSNumber numberWithInt:((int)Green)]

// strings.
NSString *path = @(getenv("PATH"));       // [NSString stringWithUTF8String:(getenv("PATH"))]
NSArray *pathComponents = [path componentsSeparatedByString:@":"];
share|improve this answer
Not sure if I should be embarrassed or elated. This is much better. – Craig Gidney Nov 29 '13 at 2:34
Elated. Better to ask and learn. – Clay Bridges May 31 '14 at 12:07

Self-answer: I didn't realize there's actually a standard syntax to do this. I'd tried @variable before, but actually I was supposed to use @(variable).

Which means that the answer to the question is: yes, they would hate it. But what exists is better anyways.

share|improve this answer
Also, literal constants don't need parens, @1, @YES. – Clay Bridges May 31 '14 at 12:12

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.