Marcelo Assis
Marcelo Assis

Reputation: 5204

Strange behavior in a simple for using uint

This works as expected:

for (var i:uint = 5; i >= 1; i-- ) 
{   
    trace(i);  // output is from 5~1, as expected
}

This is the strange behavior:

for (var i:uint = 5; i >= 0; i-- ) 
{   
    trace(i)
}

// output:
5
4
3
2
1
0
4294967295
4294967294
4294967293
... 

Below 0, something like a MAX_INT appears and it goes on decrementing forever. Why is this happening?

EDIT

I tested a similar code using C++, with a unsigned int and I have the same result. Probably the condition is being evaluated after the decrement.

Upvotes: 0

Views: 169

Answers (1)

JonH
JonH

Reputation: 33163

The behavior you are describing has little to do with any programming language. This is true for C, C++, actionscript, etc. Let me say this though, what you do see is quite normal behavior and has to do with the way a number is represented (see the wiki article and read about unsigned integers).

Because you are using an uint (unsigned integer). Which can only be a positive number, the type you are using cannot represent negative numbers so if you take a uint like this:

uint i = 0;

And you reduce 1 from the above

i = i - 1;

In this case i does not represent negative numbers, as it is unsigned. Then i will display the maximum value of a uint data type.

Your edit that you posted above,

"...in C++, .. same result..."

Should give you a clue as to why this is happening, it has nothing to do with what language you are using, or when the comparison is done. It has to do with what data type you are using.

As an excercise, fire up that C++ program again and write a program that displays the maximum value of a uint. The program should not display any defined constants :)..it should take you one line of code too!

Upvotes: 3

Related Questions