Reputation: 537
I'm learning objective-c from "Programming in objective-c" author Kochan. 3rd edition. In Chapter 8 "Inheritance" Mr. Kochan gives following explanation to the method:
-(void) setOrigin: (XYPoint *) pt
{
if (! origin)
origin = [[XYPoint alloc] init];
origin.x = pt.x;
origin.y = pt.y;
}
"The method first tests to see if the instance variable origin is nonzero (make sure you understand that test and the use of the logical negation operator ! that’s used). Recall that all instance variables are initially set to zero. So when a new Rectangle object is allocated, its instance variables, which includes origin, will be set to zero.
If the origin is zero, the setOrigin: method will allocate and initialize a new XYPoint object and store the reference to it in the origin."
Is there a logical mistake? Doesn't the "setOrigin" method allocates a new XYPoint object only if the origin is non zero?
Upvotes: 0
Views: 128
Reputation: 40159
The author is, indeed, correct.
This is why I don't like incomplete comparisons in C.
If he codes if (origin)
then that boolean expression is true for any value of origin
which is non-zero.
So, when he negates it, the boolean expression if (! origin)
is true only when origin is zero.
IMO, this is horrendous and should be coded if (origin == NULL)
which makes it much clearer.
It seems to me that he is going out of his way to teach bad coding habits. This sort of construct always gives off a Code Smell.
Upvotes: 0
Reputation: 6343
No. The "!" is a logical NOT operation in this case. When "origin" is zero, !origin is TRUE; when "origin" is non-zero, !origin is FALSE. Therefore, the next line (which allocates and initializes an XYPoint object) is only executed when origin is zero. Just as the author states.
Upvotes: 1
Reputation: 993333
Your quote says:
If the origin is zero, ...
That is, when origin
is zero (nil
), then ! origin
will be true, and a new XYPoint
will be allocated.
I don't see a logical inconsistency here.
Upvotes: 5