Reputation: 45
#include <stdio.h>
int foo(int a)
{
int i;
for(i=2;i<=a;i++)
{
if(i%5==0)
{
return;
}
}
}
int main()
{
int c = foo(10);
printf("%d",c);
}
why is 5 getting printed when it is not even mentioned what to return?
#include <stdio.h>
int foo(int a)
{
int i;
for(i=2;i<=a;i++)
{
return; //no variable is attached with return
}
}
int main()
{
int c = foo(10);
printf("%d",c);
}
and this one is returning 2. which is the first value of i
when the loop breaks due to return statement. but where is it mentioned that the function has to return i
??
Code executed in Linux.
Upvotes: 1
Views: 80
Reputation: 20244
Not returning a value from a function designed to return an int
invokes Undefined Behavior. Anything can happen. Quote from the C11 standard:
6.9.1 Function definitions
[...]
- If the
}
that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined.
Upvotes: 4
Reputation: 143
You're not returning an Integer in a method designed to return an Integer, there must be a catch that is returning the last integer created.
If you don't want to return anything, simply return void.
Upvotes: 0