return in a for loop C

Viewed 10738

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!!:)

5 Answers

The function try_this() always returns 0:

  • i is initially set to 1
  • then i is set to 0 in the initial clause of the for statement
  • if i < in, the loop body is executed and the value of i is returned, namely 0.
  • otherwise the loop is skipped and the next statement is return i; so 0 is returned too.

Regarding the main function: it ignores the return value of try_this(5) and reaches the end of its body without a return statement. This is bad style and would trigger undefined behavior for any other function, but since C99 the behavior is defined as a special case for the main function and the value 0 is returned to the startup code, which exits back to the system with a termination status of 0, which means successful execution.

if you want to store the value of 'I' i would recommend you to use "while loop"

int i = 0;
while(i < in)
{
 i++;
}
Related