1

In a test, one of my classmates wrote the following function, to flip a number:

int tukor(int n)
{
    int k=0;
    while(n!=0)
    {
        k=k*10+n%10;
        n=n/10;
    }
    n=k;
}

You will notice a complete lack of any return statements, but when cout<<tukor(1234); is run (namespaaace std is used), it outputs 4321. Now the entire class is confused as to how this is possible, even after the teacher added the lines n=0;n=12; at the end of the function. It has worked for all test cases so far.

Is this caused by undefined behavior or something similar?

EDIT: changing k before the n=k statement changes the return value, and if it is removed, the return value is 0.

Mark Gardner
  • 442
  • 1
  • 6
  • 18
  • 4
    Yes, it's an undefined behavior. The result of the function will depends on the compiler you used to build the whole program. Actually some compiler may fail to build with an error in such case. – Antwane May 15 '18 at 09:04
  • If the caller attempts to use the value returned by the function, the behaviour is undefined. Practically, undefined behaviour CAN be behaviour that passes your test cases, but that is not guaranteed to occur reliably. – Peter May 15 '18 at 09:04
  • 1
    duplicate https://stackoverflow.com/questions/1610030/why-does-flowing-off-the-end-of-a-non-void-function-without-returning-a-value-no – Yftach May 15 '18 at 09:06
  • Behaviour is undefined in that case. Implementations will have to choose a behaviour. In common implementations, the return value will be what code has left in the processor accumulator register. – Serge Ballesta May 15 '18 at 09:07
  • clang sometimes doesn't even but the ret asm instruction when there is no return statement – Tyker May 15 '18 at 09:09

0 Answers0