0
#include <iostream>

using namespace std;

int f1(int a,int b)
{
    double c=a*b*b;
    
}

int main()
{
    float number1=3.5;
    float number2=5.5;
    std::cout<<f1(number1,number2)<< std::endl;

    return 0;
}

please explain in detail. i am a beginner in c++. Any help will be appreicated

enter image description here

1 Answers1

3

Not returning from a non-void function invokes undefined behavior. The result could be anything, including a program that appears to work all the time.

While reasoning about why UB does something is not useful in general, this is possibly an artifact of a particular calling convention. The value of the 1st local variable c may be converted to an int and stored in the same register which is supposed to store the return value. Since that is the value that you meant to return, this could be the reason that the code appears to work.

Of course, whether the explanation is right or wrong, the program is still broken according to the language rules, and you can't rely on this behavior.

cigien
  • 57,834
  • 11
  • 73
  • 112
  • `The 1st local variable c happens to be stored in the same register` given that `c` is a double and the correct result, 75, is an int, It's probably more that a temporary int is stored in the register that returns the value and the double after conversion is lost. But, yeah, nit-picking, – Jeffrey Aug 06 '20 at 17:27
  • @Jeffrey Ah, I didn't think about that. I've edited the answer to be even vaguer about the cause of the right result. :) – cigien Aug 06 '20 at 17:31