Correct unsigned countdown method

I read Carnegie Mellon slides on computer systems for my quiz. On slide page 49:

Counting without signatures The
correct way to use unsigned as a loop index

unsigned i; 
for (i = cnt-2; i < cnt; i--) 
a[i] += a[i+1]; 

Better

size_t i; 
for (i = cnt-2; i < cnt; i--) 
a[i] += a[i+1];   

I do not understand why this will not be an infinite loop. I am decreasing i, and it has no sign, so it should always be less cnt. Explain, please.

+4
source share
5 answers

This seems to be an alternative expression of an established idiom for realizing the same thing

for (unsigned i = N; i != -1; --i) 
   ...;

i != -1 i < cnt. 0 unsigned, UINT_MAX, -1 ( ) cnt. , i != -1, i < cnt .

? -, , cnt - 2, cnt , 2, ( i != -1 - ). cnt . , cnt, i != -1 idiom

if (cnt >= 2)
  for (unsigned i = cnt - 2; i != -1; --i) 
     ...;

, BTW, , i, , , , i != -1, , i .

+2

, i 0, uint. , i < cnt == false.

Per Unsigned Int:

, .

C ++ uint, undefined .

+3

cnt-2 0. i >= 0.

, i >= 0 . 0, . i < cnt , i 0 . unsigned 0, UINT_MAX (2 32 - 1 32- ). , i < cnt false, .

. , . , , , .

+2

, , 0. .

unsigned cnt = 2;
for (int i = 0; i < 5; i++) {
    printf("%u\n", cnt);
    cnt--;
}

...

2
1
0
4294967295
4294967294

0 - 1 UINT_MAX. -1 , , .

, 0 5 ().

unsigned i;
unsigned cnt = 5;
for (i = cnt-1; i < cnt; i--) {
    printf("%d\n", i);
}

:

4
3
2
1
0

i = UINT_MAX, , cnt, i < cnt .

size_t "", , , C, , cnt - , i.

+2

I think you are confused with int and unsigned int data types. These two are different. In the int type (storage size 2 bytes) you have a range from -32,768 to 32,767 , while in the unsigned int type (2 bytes the storage size). you have a range from 0 to 65535 . In the above example, you are using an i variable of type unsigned int. It will decrease to π = 0, and then completes the for loop according to semantics.

0
source

Source: https://habr.com/ru/post/1670855/


All Articles