Why am I getting the correct output even though the code is logically incorrect?

Below is the code to reduce a given number to one digit by adding the digits of a number recursively.

For example, if the input signal is 845 , the output signal is 8 . 8+4+5 = 17 -> 1+7 = 8 (output)

 #include <stdio.h> #define TRUE 1 int reduceToSingle(int numb); int main() { int numb; scanf("%d",&numb); printf("Original = %d Single digit = %d\n", numb, reduceToSingle(numb)); return TRUE; } int reduceToSingle(int numb) { int sum = 0, digit = 0; for (digit = numb % 10; numb != 0; numb = numb / 10) { digit = numb % 10; sum += digit; } if (sum > 9) reduceToSingle(sum); else return sum; } 

In the above code, in the if (sum > 9) block, I did not return the function value. I just called the function. Logically, this function should give the wrong value. But when I ran the above program on my system, I got the correct sum of digits on the output. I can not understand the logic of this behavior.

+7
source share
2 answers

This is just undefined behavior, and I'm sure you got a warning. This happens in order to work - to configure the compiler settings or even change the compiler, and it will no longer be.

In this case, I suspect that eax not failing, so you get the expected value, i.e. The last return ed value for any of the calls. Therefore, when you call reduceToSingle , it will eventually reach return (with sum <= 9 ). From now on, the eax value will flow to the original caller.

+7
source

Here is what i got

 815 Original = 815 Single digit = 2009291924 

in your code reduceToSingle (numb) does not return any value in the code, so this is something like

 printf("%d %d",12); 

therefore, the garbage value is printed for a different format specifier

+1
source

All Articles