0

enter image description here i don't know that why this cpp program is returning the value without defining the return value

i was expecting that this program will return will print the error value

    #include <iostream>
    using namespace std;
    int sum(int a)
    {
        int c = a + 1; // this fucntion is returning value of c without defining
    }
    int main()
    {
        cout << sum(25);
        return 0;
    }
Chris
  • 26,361
  • 5
  • 21
  • 42
  • If you declare a function to return something but you do not return anything and you use the return value (all these things are true of your code above) then your program has *undefined behaviour*. Undefined behaviour means exactly what it says, it means that the rules of C++ define no particular behaviour for your program. So saying that your program should return a particular value is wrong but so is saying that it should not return a particular value. The behaviour of your program is undefined. – john Dec 06 '22 at 07:03
  • See dupe [Why does flowing off the end of a non-void function without returning a value not produce a compiler error?](https://stackoverflow.com/questions/1610030/why-does-flowing-off-the-end-of-a-non-void-function-without-returning-a-value-no) – Jason Dec 06 '22 at 07:07
  • In general the compiler cannot diagnose it but in this case yes. Turn on compiler warnings. https://godbolt.org/z/ePcnYc9sY. I don't know why, but in default settings most compilers compile the weirdest crap without complaining even though they could diagnose it. – 463035818_is_not_an_ai Dec 06 '22 at 08:25

1 Answers1

0

Welcome to the world of undefined behavior if you declare a function to return a value, but do not explicitly do so. The function may appear to work, or it may do something else.

This also applies if a function has a return, but control flow means it isn't reached. For instance, in the following simple function.

int foo(bool b) {
    if (b) {
        return 42;
    }
}

Turn on and pay attention to compiler warnings.

Chris
  • 26,361
  • 5
  • 21
  • 42