Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

Following is the code for reducing a given number to a single digit by adding the digits of the number recursively.

For example if the input is 845 the output 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 haven't returned the function value. I just called the function instead. Logically this function should give an incorrect value. But when I ran the above program in my system I got the correct sum of digits in output. I am unable to comprehend the logic behind this behaviour.

like image 451
svKris Avatar asked Jul 24 '12 11:07

svKris


2 Answers

It's just undefined behavior and I'm sure you got a warning. It happens to work - tweak the compiler settings or change the compiler altogether and it won't anymore.

In this case I suspect eax isn't clobbered so you get the expected value, i.e. the last value returned by any of the calls. So when you call reduceToSingle, it will eventually reach return (when sum <= 9). From then on the value of eax will trickle down to the original caller.

like image 59
cnicutar Avatar answered Nov 12 '22 03:11

cnicutar


This is what i got

815
Original = 815 Single digit = 2009291924

in your code reduceToSingle(numb) is not returning any value in the code so it is something like

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

so a garbage value is printed for the other format specifier

like image 1
Algorithmist Avatar answered Nov 12 '22 04:11

Algorithmist