Search code examples
objective-cpointerswhitespacedeclarationparentheses

Whitespace and parentheses in pointer declarations in Objective-C


I understand from earlier questions that whitespace is irrelevant in pointer declarations in Objective-C, e.g:

float* powerPtr;

float * powerPtr;

float *powerPtr;

do mean exactly the same (apart from stylistic considerations...) but is

(float *)powerPtr;

(with parentheses) the same too? Don't these parentheses implicitly "mean" that the asterisk should be in some way related to float, when it should be instead more logically related to powerPtr? (The actual pointer is actually powerPtr, not float, if I am right)


Solution

  • Your code:

    (float *)powerPtr;
    

    is not a valid declaration in (Objective-)C.

    This is an expression which casts the value in the variable powerPtr to be of type float *.

    The result of that cast is just discarded as it is not used, your compiler might give a warning - Xcode 8 issues an "Expression result unused".

    Addendum

    From your comment the syntax you show was meant to be part of a method declaration, e.g. something like:

    - (void)doSomething:(float *)powerPtr;
    

    that would occur in an @interface. The parentheses here are not being used for grouping per se but to delimit the type. As to you concern:

    Don't these parentheses implicitly "mean" that the asterisk should be in some way related to float, when it should be instead more logically related to powerPtr?

    The * is part of the type, float * is the type specification for "pointer to float". The identifier powerPtr is associated with the whole type specification.

    HTH