This is a really simple question.
Say I have a function :
int fun(int n){
if (n > 3)
return n;
else
fail(); // this function outputs error message
// and terminates the program
// no return value
}
Then there is no return value for cases where n <=3. How can this be fixed?
int fun (int n)
{
if (n <= 3) { fail(); /* Does not return. */ }
return n;
}
If you're just trying to squelch a warning about "control reaches end of non-void function" or something along those lines, you can decorate fail()
with some compiler-specific directives that indicate it doesn't return. In GCC & Clang, that would be __attribute__((noreturn))
, for example.
Example:
$ cat example.cpp
void fail(void);
int fun(int n)
{
if (n > 3)
return n;
else
fail();
}
$ clang++ -c example.cpp
example.cpp:9:1: warning: control may reach end of non-void function
[-Wreturn-type]
}
^
1 warning generated.
$ cat example2.cpp
void fail(void) __attribute__((noreturn));
int fun(int n)
{
if (n > 3)
return n;
else
fail();
}
$ clang++ -c example2.cpp
$
One possible idiom is to define fail
as returning an int and then write:
int fun(int n){
if (n > 3)
return n;
else
return fail();
}
You could declare an error code that will indicate that something is wrong with the function.
For example:
const int error_code = -1;
int fun (int n) {
if (n > 3)
return n;
fail();
return error_code;
}
Another neat way is to use boost::optional as the return value. This would indicate the return value many not be set in failure cases and this can be further checked by caller to take subsequent action.
Building on Aesthete's answer:
int fun (int n)
{
if (n <= 3) { fail(); return -1; } //-1 to indicate failure
return n;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.