1

Consider the following code...

            double total = Int32.MaxValue;
            total++;

            int previousX = 0;

            for (var x = 0; x <= total; x++)
            {
                if (x == Int32.MaxValue)
                {
                    Console.WriteLine("Int32 max reached.");
                }

                if (x < 0)
                {
                    Console.WriteLine("Counter now < 0.");
                }

                previousX = x;
            }

It would appear that, if you use var with a for loop the default type inference is of an int.

Is this correct because if the counter goes past the maximum for an int 32, instead of overflowing the stack it resets itself back to zero and then counts down from zero.

Note: previousX allows you to set breakpoints and see what the previous value of the counter "x" was.

Does anyone know why this happens?

It seems possible to get into a bit of a pickle by using var for the counter of a for loop.

9
  • I think the problem is your saying double total = Int32.MaxValue - you shouldnt be declaring total as a double in this case. Commented Nov 8, 2011 at 11:44
  • 1
    You have many questions here, can you focus on one at a time? Commented Nov 8, 2011 at 11:45
  • If I understand it right, you wish "total" to be larger than int. If so use Int64 not "double". Commented Nov 8, 2011 at 11:46
  • "[...] it resets itself back to zero and then counts down from zero.". Are you sure about that? That would really surprise me. I'd expect it to jump to Int32.MinValue and count up. And it does so on my machine. Commented Nov 8, 2011 at 11:47
  • Yes incrementing (int.MaxValue++) == Int.MinValue (Figuratively). int.MaxValue++ will equal -2147483647 Commented Nov 8, 2011 at 11:54

8 Answers 8

6

The type of x is determined by the initial value, which above is the integer literal 0.

If you want x to be a double then use the double literal 0D.

Sign up to request clarification or add additional context in comments.

Comments

3

It is important to understand that the var keyword does not mean "variant" and does not indicate that the variable is loosely typed, or late-bound. It just means that the compiler determines and assigns the most appropriate type. As you have var x=0 it determines that x is an int in order to match 0. So yes it is correct functionality.

Because of the manner in which negative numbers are represented (twos compliment) as a number wraps over its maximum value it will appear to reset and count down from -1 onwards.

The increment on x++ doesn't occur until that iteration of the loop has completed.

1 Comment

+1 for explaining what happens when the number get to its max.
2

Of course, if you increment an int past MaxValue, it goes back down to MinValue and starts to increment from there.

Comments

2

This is indeed interesting but is unrelated to the use of var. This still happens when using int (or in fact long, short etc).

The actual culprit here is that the MAX value for the loop is larger than the max value for int32. when a numeric value is incremented the number will wrap causing an infinite loop. You can declare var x, int x, short x and ALL of these would loop in a similar manner.

The nature of incrementing numeric values cause 'wrap-around'. You can try it by running the following code and observing the values befor and after the increment. (This also works if you add a decrement).

        int a = Int32.MaxValue;
        Console.WriteLine(a);
        a++;
        Console.WriteLine(a);

        short b = Int16.MaxValue;
        Console.WriteLine(b);
        b++;
        Console.WriteLine(b);

        long c = Int64.MaxValue;
        Console.WriteLine(c);
        c++;
        Console.WriteLine(c);

As an aside, the var in the code snippet posted is being set to an int by the statement var x = 0. The '0' is itself an int and hence the type of x is set to int. If you stated var x = 0F or 0L the type would be different.

1 Comment

I wonder why it wraps? Historically these sort of things used to overflow (i'm sure I have seen that). I think that this behavior may give unpredictable results if you are not carefull. Especially, using VAR in this case means you dont really think about the data type where you would if you were forced to specify it.
1

Var exact type is defined by your usage of = operator. In c# 0 is of type int so compiler is using int.

Comments

1

There's nothing special going on here. var will be inferred as Int32 because that's what 0 defaults to. If you want a long use var x = 0L. Or just long x = 0

Comments

1

The var x = 0 is going to infer that x is an integer because you are using an integer literal ("0").

Check out this related post concerning integer overflow:

why this would result in long integer overflow

Comments

0

This looks quite simple:

var x = new User()

When compiler sees this line, he replaces var with User, because that's what constructor returns. The same happens with function calls:

var x = y.ToString()

ToString() returns string, so compiler knows what to replace var with.

When you write

var x = 0

you actually call int constructor, so var is replaced with with int

You have three options:

  • double x = 0 ...
  • var x = 0.0 ...
  • var x = 0D ...

Note: D suffix is for double

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.