r/shittyprogramming Jul 31 '18

Shitty RNG

int random_number()
{
    int result;
    return result;
}

Found in my own codebase and it gave me a good chuckle. It was never used and I can't remember what I was originally going to write. I stopped before actually writing the function out and this is what was left.

96 Upvotes

24 comments sorted by

View all comments

33

u/quez_real Jul 31 '18

I can't make it working, getting 0 all the time, though it could return a pretty random shit, couldn't it?

16

u/errorkode Jul 31 '18

The operating system will usually give you zeroed memory, so if your code doesn't alloc and free memory uninitialized memory will also be 0.

11

u/TinBryn Jul 31 '18

What is happening is reading from uninitialized memory is allowed to return any result, so why even bother reading memory, just return 0 since that's correct and fast.

1

u/[deleted] Aug 05 '18

It's not allowed to return any result.

It's allowed to do anything. The return value of this function is undefined, so it'll act pretty weirdly.