Is -1 a magic number?
In this context, not really. There is nothing special about -1
... apart from the fact that it is guaranteed to be an invalid index value by virtue of being negative.
An anti-pattern?
No. To qualify as an anti-pattern there would need to be something harmful about this idiom. I see nothing harmful in using -1
this way.
A code smell?
Ditto. (It is arguably better style to use a named constant rather than a bare -1
literal. But I don't think that is what you are asking about, and it wouldn't count as "code smell" anyway, IMO.)
Quotes and guidelines from authorities
Not that I'm aware of. However, I would observe that this "device" is used in various standard classes. For example, String.indexOf(...)
returns -1
to say that the character or substring could not be found.
As far as I am concerned, this is simply an "algorithmic device" that is useful in some cases. I'm sure that if you looked back through the literature, you will see examples of using -1
(or 0
for languages with one-based arrays) this way going back to the 1960's and before.
The choice of -1
rather than some other negative number is simply a matter of personal taste, and (IMO) not worth analyzing., in this context.
It may be a bad idea for a method to return -1
(or some other value) to indicate an error instead of throwing an exception. However, the problem here is not the value returned but the fact that the method is requiring the caller to explicitly test for errors.
The flip side is that if the "condition" represented by -1
(or whatever) is not an "error" / "exceptional condition", then returning the special value is both reasonable and proper.