r/programminghorror • • Oct 26 '26 • Popcorn 1 Bravo 1

c Using garbage values to generate pseudorandom numbers

Post image

Thing I came up with instead of paying attention to class today.

I tested it on this computer (windows 11 if it matters), and the first time it's ran, an actual "pseudorandom" number is returned and the following calls return 1.0 always.

2.9k Upvotes

152 comments sorted by

View all comments

Show parent comment

12

u/vip17 Oct 27 '26

undefined behavior means anything can happen, including nasal daemons flying out of your nose

0

u/[deleted] Oct 27 '26

[deleted] — view deleted comment

10

u/vip17 Oct 27 '26

In assembly yes. But this is C or C++ code and those compilers have to conform to C or C++ standard

0

u/[deleted] Oct 27 '26

[deleted] — view deleted comment

7

u/ttlanhil Oct 27 '26

The Standard that defines how the language works.

It includes a bunch of things that result in undefined behaviour - and if you do any of them, it's valid for the computer to do anything, including delete your operating system and make demons fly out your nose.

Just because you can often get away with it doesn't mean you should (compilers can do anything including what you might actually want, but the next compiler update might break it)

0

u/[deleted] Oct 27 '26

[deleted] — view deleted comment

5

u/ttlanhil Oct 27 '26

It doesn't matter what you think would make sense.
The C standard says if you invoke undefined behaviour (and it clearly states what's valid and what's undefined), the compiler can do anything.