Any reason not to use parentheses for NSNumber literals?

I recently learned about modern Objective-C and started using the wonderful new syntax for NSNumberliterals. After reading, there are actually two ways to create NSNumbers:

// NSNumber literal
NSNumber *a = @42;

// Boxed expression
NSNumber *a = @(42);    

The end result is the same (both generate NSNumberwith a value of 42), but are there any reasons to use a literal over an expression expressed in a box for simple numerical constants?

I see two reasons for the style to prefer boxed expressions:

  • It’s easier to make out visually, especially if the number is negative or a macro (Xcode syntax highlighting does not match the color @-1or @INT_MAX).
  • It is easier if necessary to replace an undefined expression without the need to add parentheses. Like arguments for adding curly braces to single-line if statements for "future validation".

But are there any negatives or reasons to stick to the literal? The Clang page does not mention anything in the insertion section, which indicates a loss of performance or other negative side effects.

So, in the case of these simple numerical constants, is this just a case of style?

+4
source share
2 answers

They are actually compiled into the same assembly:

NSNumber *value = @42;
NSNumber *otherValue = @(42);

This results in the following optimized build:

    // NSNumber *value = @42;

movl    L_OBJC_CLASSLIST_REFERENCES_$_-L0$pb(%edi), %eax <-- NSNumber
movl    L_OBJC_SELECTOR_REFERENCES_-L0$pb(%edi), %ecx    <-- numberWithInt:
movl    %ecx, 4(%esp)
movl    %eax, (%esp)
movl    $42, 8(%esp)   <-- Here your value
calll   L_objc_msgSend$stub

    // NSNumber *value = @(42);

movl    L_OBJC_CLASSLIST_REFERENCES_$_-L0$pb(%edi), %eax <-- NSNumber
movl    L_OBJC_SELECTOR_REFERENCES_-L0$pb(%edi), %ecx    <-- numberWithInt:
movl    %ecx, 4(%esp)
movl    %eax, (%esp)
movl    $42, 8(%esp)  <--- and here again
calll   L_objc_msgSend$stub

, , :

    // NSNumber *value = @(42 + 1);

movl    L_OBJC_CLASSLIST_REFERENCES_$_-L0$pb(%edi), %eax <-- NSNumber
movl    L_OBJC_SELECTOR_REFERENCES_-L0$pb(%edi), %ecx    <-- numberWithInt:
movl    %ecx, 4(%esp)
movl    %eax, (%esp)
movl    $43, 8(%esp)  <--- Hey; it precomputed to 43. Nice.
calll   L_objc_msgSend$stub

@Zaph , .

+5

"" , , "()" , .
: 2 + 3 * 4 : 2+ (3 * 4)

@42 @(42)
@(kMeaningOfLifeAndEverything) ; -)

+2

All Articles