Thursday, July 30, 2009

C++ bool type function ? what happens when function returns false?

Let's say i calla function which returns a bool in my main fucntion, and the function is this:


bool myFunctionHere (int variable)


{


if (variable==1)


return true;


else return false;


}


let's say my variable is 2, so the function returns false. would my program then proceed to my next item in the main fucntion? what would happen exactly?

C++ bool type function ? what happens when function returns false?
That depends on how you call the function. The function just returns the bool value, you have to evaluate it somewhere to make use of it. In other words,





bool test = false;





test = myFunctionHere( 2 );


cout %26lt;%26lt; "Returned from function" %26lt;%26lt; endl


if ( test )


{


// do something


}


else


{


// do something else


}





will continue with the next statement because nothing is immediately done with the return value except save it. However,





if ( myFunctionHere( 2 ) )


{


// do something


}


else


{


// do something else


}





will execute one part of the if...else or the other because the function result is immediately used.





Hope that helps.
Reply:your main function has some variable to hold the result of 'myFunctionHere'. This variable would now be 'false'.





bool result;


...


result = myFunctionHere (2);


// result is now 'false'


// ... do something with 'result', like this:


if (result) {


... // result is true, so do thing #1


} else {


... // result is false, so do thing #2


}
Reply:your function myFunctionHere() will always return after you call it with a variable, but you dont have to accept the returned bool. After you call it and it returns, your main function will continue to run from right after the function call.

lady palm

No comments:

Post a Comment