'return in a for loop C
In the following code, would anything be returned?
#include <stdio.h>
int try_this (int in);
int main (void)
{
try_this (5);
}
int try_this (int in)
{
int i = 1;
for (i = 0; i < in; i = i + 2) {
return i;
}
return i;
}
Since there's a return in the for loop, would the code just return nothing since there's nothing after the function is called? Or would i be returned as a number, like 1(because of the declaration in try_this) or 6(because of the loop)? Thank you!!:)
Solution 1:[1]
When the first return statement is encountered, the function will return. It's easy to see that the function will start the loop and while i=0 it will return i. So each time you call try_this you'll get 0
Also, return 0; from main...
Solution 2:[2]
When you enter the for loop for the first time, i is 0 and less than the 5. Then it execute the statement return i; in for loop, which will finish executing the try_this() funciton.
Solution 3:[3]
What you are basically asking is that if the function will return something even though there is no code after the function call.
The answer is yes, it will return. It doesn't matter if there is code later or not. The function will return (in this case 0) It's just that there's nobody to catch it.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | David C. Rankin |
| Solution 2 | LF00 |
| Solution 3 | Parth K |
