I have a function in a C++ program returning a string.
On certain conditions, e.g. if the function encounters an error or so, I want to return a special value telling the caller that something has gone wrong.
I could basically just return an empty string "", but the function does need the empty string as normal return value.
- How can I accomplish this?
- Do I have do create a special data structure that for my function that holds a bool if the function was successfully run and a string containing the actual return value?
This sounds like a usecase for exceptions.
If you don’t want to or can’t use exceptions, you could change the function’s interface
Though most often, i’ve seen the return value is used for the actual result, and an error pointer is passed
This has the benefit that you can default the error argument pointer to
0and code that can ignore the error (because it could live with an empty string return, for example, or if it knows in advance the input is valid) would not need to bother: