> Programming C++ Return function question?

Programming C++ Return function question?

Posted at: 2014-12-18 
You've declared an int-returning function, so every exit from the function must return a value. You don't say what to return empty() is something else.

I thought failing to return a value of the correct type was an error in modern C++, but your compiler allows it. At the very least, it is "undefined behavior". Every CPU register and every memory location has a value in it at all times. Whether the return value is expected to be in a register or on the stack, the caller will find a return value--even if you didn't provide one.

Add an else clause or a simple return statement after the if that says what you do want returned when empty() is not 1.

your compiler should have complained about that.

when empty()==1 you are falling off the end of a non void function. So you get a random value returned.

one way around that is:

int top(){

if (empty() == 1)

//do nothing

else

return arr[t];

return -1;// or some other value

}

Without more of your code, it's hard to say. But that typically means that you aren't initializing the values of your array, so the default value of the variables in the array are the integer equivalents of whatever that memory space had been used for previously.

printf("Output: %d \n",top());

int top(){

if (empty() == 1)

//do nothing

else

return arr[t];

}

Question: When empty() == 1, it exits the loop but why does it return me some random int values? (show in printf output). How to fix this?