Special values

Should the code return -1 for special cases, like errors? Or initialize a variable with -1?

The -1 convention is often used with C/C++ functions returning an integer that is normally positive or, at least, non-negative. So, in case of an error, when there is no value to return, -1 is used as a kind of "not applicable".

The general case, however, is that we have a regular value (to return from a function or to memorize as a current state or a result), and special cases when there is no applicable value.

We need there a value that can be stored in that variable and can be distinguished from the "regular" values. It plays the role of a null value.

The value -1 fits the bill if all regular values are non-negative and the type of the value is a signed integer. The value 0 is also usable if all regular values are strictly positive.

However, what we really need is a null value.

In languages, like python or javascript, with no compile-type fixed types, the most natural value to store there is None or null or whatever the language provides.

In languages with compile-type fixed types, what we really need is a nullable type - a type containing all "regular" value, plus an additional "null" value. Without language support, we need to choose a value that we can be sure it cannot appear as a regular value. Modern languages offer quite often a nullable variant of other, "regular", types. For instance, in C++ we have std::optional<int> that can have all the int values plus a special null value, or in C# we have int? that has the same semantic.

As a final thought, regular pointers or references are nullable, in the sense that a pointer variable can hold the address of some variable, or it can have the special value null. Some languages offer more recently a non-nullable variant of the regular pointer.