Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meaning of -1 in Programming [closed]

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.

like image 348
Daniel Underwood Avatar asked Dec 08 '22 14:12

Daniel Underwood


1 Answers

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.

like image 193
Servy Avatar answered Dec 11 '22 09:12

Servy