Home > OS >  why this recursion print 0 after some non-zero values?
why this recursion print 0 after some non-zero values?

Time:03-05

this is infinite recursion, I am confused why this is printing 0.

#include <stdio.h>
void go(int x)
{
    printf("%d",x);
    go(x x);
}
int main()
{
    go(2);
    return 0;
}

CodePudding user response:

The program has undefined behavior, because it will eventually result in signed overflow in x x.

CodePudding user response:

When you add an integer to itself repeatedly, you will eventually reach a point where an integer datatype is too small to hold the result of the multiplication. This will eventually result in a zero (or undefined, see below) value.

Adding an integer to itself, is the same as multiplying by two. If your datatype is signed the behaviour of the resulting overflow is undefined. If the dataype is unsigned you will eventually reach a zero value.

CodePudding user response:

The program has undefined behavior (UB) because of the eventual integer overflow. So there are no guarantees of any form of output or behavior.

One explanation for why it prints zeroes as one possible outcome of overflow UB, is that on a 32 bit system it will overflow at the point of 1073741824 1073741824. This equals 2^31 but INT_MAX will be 2^31 - 1, hence the overflow. A common behavior when that overflow happens is to switch to the binary representation of the number 2^31, which in 2's complement will be -2147483648.

And then in the next step -2147483648 -2147483648 ends up as zero. This isn't particularly logical (it's UB), I guess you can think of it as -2147483648 -2147483648 = -4294967296, this being equivalent to binary representation 0xFFFFFFFF00000000. Truncate that down to 4 bytes and you get zero.

The reason why I keep mentioning binary representation is that integer overflow is very likely well-defined behavior in the actual CPU. It will just wrap-around as an unsigned number will, discard anything that won't fit and set an overflow flag.

And from there you'll have endless 0 0, unless the recursion wasn't optimized but crashes in a stack overflow.

  •  Tags:  
  • c
  • Related