Re: Is pointer syntax logical?
Re: Is pointer syntax logical?
- Subject: Re: Is pointer syntax logical?
- From: Alastair Houghton <email@hidden>
- Date: Thu, 26 Jul 2007 11:14:01 +0100
On 26 Jul 2007, at 08:58, Bob Ueland wrote:
Here we are declaring a method that takes a fraction object as
input and returns a fraction object as output. Here we clearly see
that the asterisk belongs more to the type Fraction then to the
variable f.
So if I was to define the syntax of C I would rather define the
declaration of a pointer like this:
(Fraction *) aFraction;
But when K&R defined the syntax of C they used (what from my naive
point of view doesn’t seem logical)
Fraction *aFraction;
So my question is why the syntax for pointers looks like it does.
Is there any logical explanation.
Yes.
The asterisk is *not* a part of the type, it's a part of the
declaration; it binds to the right, *not* the left. Put another way,
when you say
Fraction *aFraction;
what you're saying to the compiler is that
I wish to declare that "*aFraction" (i.e. the thing pointed to by
"aFraction") is a Fraction
*NOT*
I wish to declare a variable "aFraction" of type pointer-to-Fraction
The difference is subtle but can be critical---e.g. if you write
Fraction *aFraction, bFraction;
then the "*-is-part-of-the-type" camp get confused because bFraction
will *not* be a pointer variable. If you read it the same way the
compiler does, then this is obvious, because you're saying that
"*aFraction" is a Fraction, and "bFraction" is a Fraction
Some people *insist* on writing the asterisk (or in C++ the
ampersand) in the wrong place, e.g.
Fraction* aFraction;
and then claim that you shouldn't write more than one variable in
each declaration (because doing so highlights the fact that their
declaration is intentionally written in a different manner than that
in which the compiler understands it---which is never a good idea).
I've actually heard some of these people claim that the C declaration
syntax is "broken", which is ironic because it's really their
understanding and/or use of it that's broken. These people include
some quite eminent computer scientists, which is a shame because it
only serves to unnecessarily confuse matters.
As far as the Objective-C parameter syntax goes, it seems to resemble
the C cast syntax. I think it had to have the brackets because it
would look odd without them, and it does seem more aesthetically
balanced with the parameter names *outside* of them. I don't have
much else to say on that subject though.
Kind regards,
Alastair.
--
http://alastairs-place.net
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden