Search code examples
c++for-loopcycle

For cycle bugged?


I made a for cycle to calculate the population of an alien species growth. This is the cycle:

int mind = 96;
int aliens = 1;
for (int i=0; i <= mind; i++)
{
    aliens = aliens * 2; 
}
cout << aliens;

Oddly, the cout is returning 0, and it makes no sense, it should return a very high value. Is the cycle badly coded?


Solution

  • The issue is simple. you have a int (most likely 32-bit signed integer). The operation you're doing (x2 each cycle) can be expressed as a shift arithmetic left. Beware the powers of 2! Doing 1 << 31 on a 32-bit signed integer will effectively go back to 0 (after an overflow).

    Let's see how your loop goes.

    0 2
    1 4
    2 8
    3 16
    4 32
    5 64
    6 128
    7 256
    8 512
    9 1024
    10 2048
    11 4096
    12 8192
    13 16384
    14 32768
    15 65536
    16 131072
    17 262144
    18 524288
    19 1048576
    20 2097152
    21 4194304
    22 8388608
    23 16777216
    24 33554432
    25 67108864
    26 134217728
    27 268435456
    28 536870912
    29 1073741824
    30 -2147483648 // A.K.A. overflow
    31 0
    

    At this point I don't think I need to tell you 0 x 2 = 0 The point being: use a double or a integer variable that's at least mind + 1 bits long