Reputation: 39
What means
failing to provide a return after a loop that contains a return is an error
in "C++ primer fifth", page 295?
Especially, the compiler does not detect this error, what happens at run time is undefined.
I use the book sample like: (vs2013)
#include "stdafx.h"
#include "iostream"
#include "string"
using std::string;
bool str_subrange(const string &str1, const string&str2) {
if (str1.size() == str2.size())
return str1 == str2;
auto size = (str1.size() < str2.size()) ? str1.size() : str2.size();
for (decltype(size)i = 0; i != size; ++i) {
if (str1[i] != str2[i])
return false;
else
return true;
}
}
int _tmain(int argc, _TCHAR* argv[]) {
if (str_subrange("lyc", "talent"))
std::cout << "yes" << std::endl;
else
std::cout << "nope" << std::endl;;
system("pause");
return 0;
}
It works well, I want to know which situations that "return" is must.
Upvotes: 2
Views: 135
Reputation: 67
In such case where using loops, if conditions, always return from end of function, assign a return value at start and update that value based on conditions.
Upvotes: 0
Reputation: 29266
If size
is 0, the for loop never executes and so the method has no return value.
Upvotes: 4
Reputation: 1499
If size
ends up as 0 (e.g. one of the strings is ""), your loop is never run. If the loop never runs, then what is returned is undefined, because the program won't write a result to be returned to the caller of the function. The result you get is whatever was preexisting in the memory contents of where the return value is expected on the stack.
When you decide to return values inside loops, or other grouping statements (e.g. "if"), always manually run your code in your head checking to ensure you return a value on every valid path and even if loops don't run.
Upvotes: 2