End a void function?

A

Alexander

How can I end a function that is declared 'void'? For other functions
I would simply return, but is it possible to end the function
explicitly, for example under a condition? I could, of course, simply
make the rest of the code only execute under the contrary condition
(which is what I did for the task), or declare the function to be
'bool', and return, but these are both kludges, inelegant options that
avoid the solution of the problem. I don't need it for a particular
task, it just got me interested. Anyone has an answer?
 
F

Francesco S. Carta

How can I end a function that is declared 'void'? For other functions
I would simply return, but is it possible to end the function
explicitly, for example under a condition? I could, of course, simply
make the rest of the code only execute under the contrary condition
(which is what I did for the task), or declare the function to be
'bool', and return, but these are both kludges, inelegant options that
avoid the solution of the problem. I don't need it for a particular
task, it just got me interested. Anyone has an answer?

In a function declared void you can exit by simply stating:

return;

wherever you want to.

For differences of style - or for guidelines imposition - some people
prefer to (or have to) have only a single exit point for any function,
in such case you'd have to conditionally skip parts of the function till
you reach its "normal" exit point (the closing curly brace).
 
A

Alexander

OK. Thanks to all. I just read somewhere (and tested) that returning a
value from a void function is illegal in C++; I misinterpreted like
'returning is illegal', and didn't think about *that*! Thanks again
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,143
Latest member
SterlingLa
Top