1 hour ago · Tech · 0 comments

Have you ever wondered why return -1 is used in a program when nothing is found? You might have thought that is because -1 doesn't make sense in the context, so it is safe to agree to use some arbitrary value that is not used normally. In fact, you would be correct. But it goes deeper than that. -1, as well as \0 string termination sequence, None in Python, null in JavaScript, nil in Go and so on — all of them share the same commonality: they are sentinel values. Their purpose — to simplify and streamline program logic. Instead of introducing a new concept or a variable, we can reuse existing data and leverage logic that we already have. Also, often times it is more elegant. Even if it doesn't look like it at the first glance. For example, -1 is pretty much the inverse logic: suppose you use an 8-bit number. 0000 0000 is zero, 0000 0001 is one and so on... Well, -1 in this case will be exactly 1111 1111 following two's compliment. Pretty elegant way of sending a special signal without…

No comments yet. Log in to reply on the Fediverse. Comments will appear here.