1

Why p() fucntion return a value? which is returned by call() fucntion . when i called function p() . it has not any return statement , but autometicaly return value of call() fcuntion .

int call(int x)
{
    return x;

}
int p(int k)
{
    call(4);

}


void solve()
{
    cout<<p(9)<<endl; //output is x

}

int main()
{
   
    solve();

}
  • 8
    Pretty sure this us Undefined Behavior, so anything can happen. (_Possibly_ you are seeing a result because of the way the stack is organized, but the answer is "because it is UB"). – 001 May 21 '22 at 11:50
  • 5
    Not returning a value from a function that should return a value invokes *undefined behavior*. It just accidentally "works" in your case (presumably because the return value of `call` is still stored in the correct register when `p` ends) – UnholySheep May 21 '22 at 11:51
  • 2
    [What are all the common undefined behaviours that a C++ programmer should know about?](https://stackoverflow.com/q/367633) – 001 May 21 '22 at 11:52
  • 3
    If you crank up the warning level, [the compiler should flag this](https://wandbox.org/permlink/MMFVcd8KBTdtzx74). – Paul Sanders May 21 '22 at 12:29
  • 2
    `p` function does not return a value. It's signature claims that it is going to return a value, but it does not. The program is ill-formed. Anything can happen. If you are really unlucky, it can appear to work (kind of, sort of). – Eljay May 21 '22 at 12:55
  • 1
    On most current platforms, the return value of a function is the content of the **R0** register. Knowing this can explain the observed behavior: `call(4)` places the integer 4 in **R0**, and since `p` doesn't contain a `return` statement, the compiler just didn't write to **R0** at all, and you get the value in `main`. But as everybody already wrote, this is *Undefined behavior*. Other compilers or other optimization levels will produce different result. For example, on MSVC in debug mode, stack is padded with special pattern to show uninitialized values and you might receive `0xcccccccc`. – prapin May 21 '22 at 14:33
  • See historical explanation here for old C code without `void` https://stackoverflow.com/questions/4644860/function-returns-value-without-return-statement/58424810#58424810 – Sebastian May 21 '22 at 16:31

0 Answers0