Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Dummy question 2

Status
Not open for further replies.

maur3r

Technical User
Aug 28, 2006
34
0
0
PL
Can somebody please tell me why the first code works and second not (of course the only difference is changing type of i var. from int to unsigned int) and maybe evaulate a solution how to change a first code using unsigned type and not receive an error.

Code:
int a[3];
a[0]=0; a[1]=1; a[2]=2;
unsigned int i=0;
for(i=2;i>=0;i--)
cout<<a[i]<<endl;

Code:
int a[3];
a[0]=0; a[1]=1; a[2]=2;
int i=0;
for(i=2;i>=0;i--)
cout<<a[i]<<endl;

Regards, Martin

(OS and comp.)
using Linux and gcc
 
In a for loop, the counter is decremented and then evaluated to continue the loop. With unsigned data types, decrementing a value of 0 will result in a value that's the maximum value for that data type.

The same bit pattern that represents -1 in a signed 16-bit integer represents +65535 in the unsigned equivalent.

for (i = 2; i >= 0; i--)

is evaluated the same as

for (i = 2; i > -1; i--)

which will NOT work with unsigned integers because they can never be negative.

In plain English, your loop says:

Repeat this while i is greater than or equal to 0 and decrement i after each time through.

When i equals 0, the loop continues. After that iteration, i is decremented again (from the previous value of 0) and checked to see if it's less than or equal to 0. An unsigned can never be less than 0, which means the generated code will never evaluate i as less than zero to terminate the loop.

Lee
 
unsigned int i=0;
for(i=2;i>=0;i--)

I get
$ gcc -W -Wall -ansi -pedantic -O2 foo.c
foo.c: In function `main':
foo.c:24: warning: comparison of unsigned expression >= 0 is always true



--
 
Now I see it clearly. Thank you

Regards, Martin

(OS and comp.)
using Linux and gcc
 
also, from what maur3r stated, when you subtract an unsigned long you will get a wrap around, so to use the first algorithm you posted start from 3 end at 1, when you store in the array however youd have to use a[i-1], which i believe is not good style but if you wanted to keep your first convention the way i suggested should work.

Regards,
Mhanny
 
Status
Not open for further replies.

Similar threads

Part and Inventory Search

Sponsor

Back
Top