Pergunta

I hate to ask this question on here, but I have searched both SO and Google to no success. I have seen in many places statements such as while(var != -1) and other statements, often loops, containing some sort of reference to -1. Is there a certain meaning to the use of -1, or is it just used as giving an integer representation of a boolean, or something like that? I have mainly seen this in C# programming if that is any help.

Foi útil?

Solução

in C# -1 is just negative one. They're comparing a number against a number, seeing if it is indeed equal to negative one.

It's not uncommon to have an integer field that should only have positive values (for example, when representing an index in a list) and in such cases -1 is sometimes used to represent "not a valid value", for example, there is no item, and hence no index. They use -1 because an int is not nullable; they cannot assign null.

In theory this is probably a bad practice; it's using a "magic value" to mean something more than it really should. Ideally if "there is not valid" is a valid thing for the variable to represent it should be a nullable integer (int? or Nullable<int>) but this is an old convention (carried over from other languages without a feature for nullable ints) so it's hard to eliminate entirely.

Outras dicas

Nothing special about it. It's just that in most frameworks and libraries, functions or methods that return an index of an element in a collection will return -1 when whatever you're looking for isn't in the collection.

For example, the index of the character b in the string foo would be -1 in JavaScript, .NET and, as far as I remember, Java as well.

So many devs have burned a rom in their minds saying that -1 is the index for not found items. Now you know why.

If you know that an int should always contain positive value (for instance an item count or an index in a list, -1 can be a kind of "reserved value", so you would for instance assign the count to -1 and as long as it's -1, you know no real value has been put in there, a bit like a "null"

other than that I don't think there's any special meaning to -1

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top