peppermint
peppermint

Reputation: 11

why does '%d' not return the right value?

int a = 31; 
int b = 1; 

while (a)
{
    b = (2 * b) + 1;
    a--;
};

printf("count:%d \n", b);

it prints the right number when a is smaller than 31. Starting from 31, it just prints -1 and I don't understand why. How can I fix it?

Upvotes: 1

Views: 86

Answers (4)

Michiel Pater
Michiel Pater

Reputation: 23023

The integer overflows and will become negative.

To fix this, you can change the int variable b to long.

long b = 1;

Upvotes: 2

Eugene Sh.
Eugene Sh.

Reputation: 18299

The while loop is terminated when a becomes 0, since the condition

 while (a) ...

evaluating to

while (a != 0)...

It will happen after the loop is executed 31 times with the following expression in it:

b = (2 * b) + 1;

while the initial value of b is 1. It will generate the series: 1, 3, 7, 15... 2^(k+1)-1, while k is the iteration number (starting from 0 for initial value). So for k=31 the value would be 2^32-1. 2^32 is overflowing the 4-byte integer storage type, which is resulting in an undefined behavior. But some compilers are usually handling the overflow by just throwing away the overflowed leftmost bits, so the truncated 2^32 is becoming 0. So 0-1 = -1 and this is your result. But again, no standard is guaranteeing that you will get this result, so you should never rely on it.
To fix it, you can use a bigger storage type, like long, and use %ld for printf.

Upvotes: 1

Fernanda Brum Lousada
Fernanda Brum Lousada

Reputation: 371

It's ok the @EugeneSh. answer, but the series don't start in 1, but 3. And to print all values of b, the printf needs to stay into the while loop.If the intention were starting in 1, the printf needs to be the first line into the while loop.

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 310910

In the two's complement internal representation of type int if its size is equl to 4 bytes the sign bit is equal to 2^31.

Thus then you multiply b by two when b is equal to INT_MAX then the sign bit is set and the number is converted to -1.

That is while the sign bit is not set you get poistive numbers 1, 3, 7, 15 and so on. As soon as the sign bit is set you get negative number -1 that has internal representation with all bits including the sign bit are set.

Upvotes: 1

Related Questions