Pac0
Pac0

Reputation: 23174

In C#, must an int be positive, negative or zero exclusively?

TL; DR;

Does the C# language ensure that an int must have one and only one of the following properties?

  1. strictly greater than 0
  2. strictly less than 0
  3. equals to 0

To be precise with an example, is this assertion guaranteed to never fail ?

public void CheckFacts(int n) 
{
    int trueFacts = 0;

    if (n > 0) trueFacts += 1;
    if (n == 0) trueFacts += 1;
    if (n < 0) trueFacts += 1;

    Assert.AreEqual(trueFacts, 1); 
}

Follow-up question : If yes, is that true as well for the various integer types ? (uint, long, ulong, sbyte, byte, short, ushort, ...)


For those who might think that this question is a bit off, don't forget that computer numbers can be surprising.

For instance, this is not the case that a double must be positive, negative or zero exclusively. It can be NaN, it can be +0.0 or -0.0, 3 values that will cause the above assertion to fail.


EDIT:

Someone made the remark that I somehow spent time writing this question but not one minute looking at the specs. I actually spent quite a lot of time reading : https://msdn.microsoft.com/fr-fr/library/system.int32(v=vs.110).aspx , because int is supposed to be an alias for System.Int32. I am honestly not sure that there was a clear cut on my question. Also, I thoroughly searched questions on SO, because I thought that someone must have been asking this before. Sorry if such question seems obvious for some people, it was not to me.

Upvotes: 2

Views: 4195

Answers (1)

Bathsheba
Bathsheba

Reputation: 234785

Yes you are correct.

An int in C# is a 2's complement integral type with no unused bits. Every bit pattern is associated with a unique integral value. There is no room for things like infinities, "not a numbers", &c. (That uniqueness also applies to uint, long, ulong, sbyte, byte, short, ushort, &c.)

For the avoidance of doubt, there is no signed zero, which is a property of signed magnitude and 1's complement schemes.

Note also, for an IEEE754 floating point double, your code would work with a signed negative zero, since 0.0 is defined to be equal to -0.0, and 0.0 > -0.0 is false. You are correct that it would fail on NaN.

Reference: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/int

Upvotes: 10

Related Questions