-2

I'm trying to execute the below code, since the function has no return value but it was defined with integer return type. how it was running without any error.

#include <stdio.h>
int fn(int a, int b){
  int temp = b;
  a = 2*temp;
  b = a;
}
int main()
{
  int x,y,printval;
  scanf("%d%d",&x,&y);
  printval = fn(x,y);
  printf("%d", printval);
  return 0;
}

i Expect the output be error but it was resulting in 40(input:10,20)

kamalnath L P
  • 37
  • 1
  • 6
  • 1
    in C++ it is up to you to return correct value. If you do not return any value it is no error. And it can be treated as undefined behavior. In this case most probably current value stored in eax registry was returned (most possibly temp value) – Eltu Jul 19 '19 at 10:34

1 Answers1

2

Your code has undefined behavior, that means anything is possible; you shouldn't depend on it at all.

[stmt.return]/2

(emphasis mine)

Flowing off the end of a constructor, a destructor, or a non-coroutine function with a cv void return type is equivalent to a return with no operand. Otherwise, flowing off the end of a function other than main or a coroutine ([dcl.fct.def.coroutine]) results in undefined behavior.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405