fineashell
fineashell

Reputation: 41

Function returning wrong value

I don't understand the output from this code:

#include <stdio.h>
long func(long pass)
{
    long ret;
    long i = pass;

    if (i == 6)
    {
        printf("i=%ld\n",i);
        return i;
    }
    printf("ended\n");
}

void main()
{
    int j;
    long it = 0;
    for(j = 0; j < 12; j++)
    {
        printf("%ld\n",func(it));
        it++;
    }
}

The output shows "ended" and "6" every time except when it reaches i=6, that time it prints i=6 and 6.

WHY? It shouldn't be going inside i == 6 every time right?

Upvotes: 0

Views: 331

Answers (4)

PU.
PU.

Reputation: 148

When i is not equal to 6 it throws the warning as ::  warning C4715: 'func' : not all control paths return a value
and returns an indeterminate values and printf("%ld\n",func(it)); prints that value like,
ended
1
ended
1
ended
1
ended
1
ended
1
ended
1
i=6
6
ended
6
ended
6
ended
6
ended
6
ended
6

Upvotes: 0

Harminder Singh
Harminder Singh

Reputation: 1

the control reaches the end of long func(long) because return statement is inside the if condition which fails if 'i' is not equal to 6.

Upvotes: 0

M.M
M.M

Reputation: 141648

When i == 6 is not true , then execution reaches the end of func without encountering a return statement. This causes the function to return an indeterminate value.

Then the line printf("%ld\n",func(it)); accesses the indeterminate value, which causes undefined behaviour.

Upvotes: 2

Chris Dodd
Chris Dodd

Reputation: 126468

When i is not equal to 6, you run off the end of the function without a return statement, which gives you undefined behavior -- anything might happen.

In this case it probably just returns whatever happens to be in the hardware return register at the end of the function, which might just be the constant 6, as the compiler might have put it there for the comparison. A different compiler (or even the same compiler run on a different day) might give you a different result.

Upvotes: 3

Related Questions