Using a variable in its own declaration in recursion

时间:2015-07-31 20:00:54

标签: c recursion

Using a local variable in its own initialization usually has no effect but doing it with recursion causes strange values. Why is there undefined behavior in the recursion but not outside of it?

#include <stdio.h>

void recurse(int count);

int main()
{
    int j = j + 1; // a weird thing to do but its just 1
    printf("%d\n", j);
    j = j + 1;
    printf("%d\n", j);
    j = j + 1;
    printf("%d\n", j);

    recurse(1);

    printf("\n");
}

void recurse(int count){
    int i = i + 1; // the really weird part
    printf("%d ", i);

    if(count < 10)
        recurse(count + 1);
    return;
}

Output:

1
2
3
32737 1 32737 1 1 1 1 1 1 1

The large numbers are not always the same for each execution.

2 个答案:

答案 0 :(得分:3)

This is an example of undefined behavior.

Because the value can't be known before it is assigned, you can't predict what will happen. Running the same code on a different machine, or compiled with different settings, can yield different results.

答案 1 :(得分:3)

Local variables (not initialized) have indeterminate value in C.

Reading them prior to assigning a value results in undefined behavior.

Nice quote from wikipedia article

In computing, an uninitialized variable is a variable that is declared but is not set to a definite known value before it is used. It will have some value, but not a predictable one. As such, it is a programming error and a common source of bugs in software.

However, it is important to mention that in C, static and global variables not initialized will have the value = 0.