简体   繁体   中英

Unexpected Behaviour on calling simple C function

On Running following c code the output is neither 0 nor a constant number and even after trying to use some print statements in random block, i can't not conclude what's happening

#include <stdio.h>

int random(int start, int end); // start, end are just added to make sure that results are not same due to caching.

int main(void) {
    int i;
    for (i=0; i<10; i++)
        printf("%d\n", random(0, i));

    return 0;
}

int random(int start, int end) {
    int out_num;
    return out_num;
}

$ gcc -o ./compiled/bogo_binary_search bogo_binary_search.c && ./compiled/bogo_binary_search 
0
32653
32653
32653
32653
32653
32653
32653
32653
32653
int random(int start, int end) {
    int out_num;
    return out_num;
}

The local variable out_num is uninitialized . It could have any value, or your program could crash when you try to use it.

An uninitialized variable has an indeterminate value. That only means that the standard does not say what the value should be. The compiler could use a fixed value or a random one if it wants. What it most often does in practice is to use whatever was in memory without setting it. So in one sense it is random, because it's not completely predictable.

But as a random generator it is very poor. Some values are way more possible than others. All zeros is extremely common. And if you run the program many times in a row on one machine, it's quite likely that whatever value you got will be the same next time.

And of course, it's undefined behavior to read an uninitialized variable, so i theory, the compiler could do anything. But it's very likely it will just print the value, whatever it is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM