Search code examples
c++crandomglobal-variables

I have a random Number Generator that uses a XOR shift algorithm, using a global variable. Is there another method to accomplish this?


I built this "Random" number Generator, and it works exactly like its supposed to. But I feel like the use of a Global variable in this way is cursed, and there must be a better way of accomplishing the same thing.

unsigned int State = 1804289383;
unsigned int get_random_U32_number() {
    unsigned int Number = State;
    Number ^= Number << 13;
    Number ^= Number >> 17;
    Number ^= Number << 5;
    State = Number;
    return Number;
}

Not sure what else to try, I can't use any built like function like rand() for this project.


Solution

  • Another approach, slightly different from @dbush's answer:

    unsigned int get_random_U32_number( void ) {
        static unsigned int State = 1804289383;
    
        unsigned int Number = State;
        Number ^= Number << 13;
        Number ^= Number >> 17;
        Number ^= Number << 5;
        State = Number;
        return Number;
    }
    

    The change to get_random_U32_number( void ) makes it explicit that the function takes no arguments.