-1

So i've been building a simple console game in c++ where I am using the rand() function from stdlib.h. I have recognized that i got different results from the rand function if I was executing the program in debug mode or without debugging.

Here is my code where I use the rand function:

void Game::SelectHiddenWord(Fstring &word) {
    std::vector<Fstring> WordList{ "plan","planet","planes","radios","gamers","images",
    "amigos","micros","macros","frogs","raids","roads","paris","smog","cars","macs","scam","some","farm","fair",
    "jam","rat","map","zig","zag","isogram","amorist","roaming","mirages","soaring","cargos","disarm","isobar"
};
    int32 Length = WordList.size();
    int32 randomNumber = std::rand()%Length;
    word = WordList.at(randomNumber);
}

So basically I have a wordlist with isograms and I am using the rand function to generate an integer which I will use as my index when selecting a word from the wordlist. I found that every time I was executing the program the randomNumber integer was always 14 which would then give me the word "smog" from the wordlist. First I thought that this maybe was a bug since I've read that the rand() function isn't the best to use to generate random numbers. So I started the program in debug mode and I found out that I the randomNumber integer now was 32 which would give me the word "disarm" from the wordlist. And this happend every time I was using debugmode.

So on startup without debugging I always get the word "smog" and on startup with debugging I always get the word "disarm" so I can really just play around with two words.

So is this some sort of bug with the rand() function that it will behave differently when executing the program in debug mode and without debug mode?

I'm trying to learn c++ and I couldn't find any information about the rand function behaving differently so I do not know how I can fix this issue. So if any of you guys know how to fix this issue, so that the rand() function will behave the same and generate the same number independently if I am using debug mode or without debugging. Or maybe I need to use another function to generate my random numbers?

Any help will be appreciated!

Edit:

I do not want to know why the rand() function generates the same value everytime. When I start the program without debugging the rand() always generates the number 14, and I want this to happen. But if I start the program in debug mode the rand() always generates the number 32. But I want the rand function to always generate the number 14, independently if I execute the program in debug mode or without debugging.

So the question is about why the rand() function is behaving differently and generating different numbers if it is executed with or without debugging. I don't even know if it's possible to answer this, maybe it could just be something with my machine.

My testing code:

void Game::Print() {
Fstring HIDDEN_WORD{}; //This MUST be an isogram
SelectHiddenWord(HIDDEN_WORD);

MyHiddenWord= HIDDEN_WORD;
std::cout << MyHiddenWord << std::endl; //This prints "smog" to the screen if I start the program without debugging, 
                                       //and if I debug the program it prints "disarm" to the screen

My main method:

Game MyGame;
int main() {
 MyGame.Print();
}

I am using Microsoft Visual C++ compiler.

Jacce
  • 172
  • 1
  • 2
  • 11
  • 1
    You should seed your random number generator 1 time in at the begining of main(). – drescherjm Sep 16 '18 at 19:22
  • 1
    I am not sure why the release and debug rand() result is different. – drescherjm Sep 16 '18 at 19:23
  • 2
    @πάντα ῥεῖ: I think the dup does not answer the question; actually I'd expect that debug and release behave the same, even if srand is not called explicitly: "std::srand() seeds the pseudo-random number generator used by rand(). If rand() is used before any calls to srand(), rand() behaves as if it was seeded with srand(1). Each time rand() is seeded with srand(), it must produce the same sequence of values on successive calls." – Stephan Lechner Sep 16 '18 at 19:30
  • @StephanLechner What question after all? – πάντα ῥεῖ Sep 16 '18 at 19:40
  • @StephanLechner you are very correct. Should we reopen it and then close it again as off topic, questions that seek debug help should contain mcve? – Öö Tiib Sep 16 '18 at 19:41
  • @πάντα ῥεῖ: I'd say it's about "So The question is about why the rand() function is behaving differently and generating different numbers if it is executed with or without debugging." – Stephan Lechner Sep 16 '18 at 19:42
  • 1
    To be an answerable question we need a minimal example that produces the result you are seeing so we can test. We also most likely need to know the compiler you are using. – drescherjm Sep 16 '18 at 19:43
  • I recommend seeding the rand() function with a fixed value at the start of the program, e.g. `srand(1);` I would expect you to get the same values with or without debugging then. Mind you I would have expected that anyway. – john Sep 16 '18 at 19:44
  • 2
    A bug in your code still seems the most likely explanation to me. Try writing a one line program that does nothing except call `rand`, see if you get different results with or without debugging then. – john Sep 16 '18 at 19:47
  • ***A bug in your code still seems the most likely explanation to me.*** I would agree with this. Although there have been compiler / library bugs its unlikely this would be broken. – drescherjm Sep 16 '18 at 19:49
  • 1
    @πάνταῥεῖ the OP *wants* to get same sequence but somehow does not. – Öö Tiib Sep 16 '18 at 19:52
  • According to James Kanze in https://stackoverflow.com/a/11883505/2785528, "Debug build and release build are just names. They don't mean anything." But Quora says the two modes use different optimizations. (Note: I have never used either 'mode' and I think that is because I've never used MS.) So there are several places to research -- and I'm guessing that none will be a C++ language issue. The tools you know. – 2785528 Sep 16 '18 at 19:53
  • Where does `Fstring` come from? – drescherjm Sep 16 '18 at 19:58
  • @drescherjm "using Fstring = std::string;" So it is just a string. – Jacce Sep 16 '18 at 19:59
  • @ÖöTiib Sure and, the same seed number given when calling `srand()` should have that behavior. The proposed duplicate explained that in depth, and the OP misses to give a [MCVE] so what? – πάντα ῥεῖ Sep 16 '18 at 20:00
  • Where is `MyHiddenWord` declared I am trying to reproduce this. – drescherjm Sep 16 '18 at 20:10
  • It is declared as a private Fstring (string) in the Game's header file. It is just declared like " Fstring MyHiddenWord;" and I am also using "#Include Game.H" in the Game.cpp file. – Jacce Sep 16 '18 at 20:15
  • In Visual Studio 2017 15.7.6 32 bit I get the same answer "macros" in regardless of debug or release or debugging. – drescherjm Sep 16 '18 at 20:17
  • I also get "macros" in 64 bit from the same compiler using the minimal example I put together using the functions above and main. – drescherjm Sep 16 '18 at 20:26
  • @drescherjm Well I guess I've f****d up my compiler in some way then. I appreciate the effort you put in though. Thanks :) – Jacce Sep 16 '18 at 20:27
  • Maybe something else is going on. Did you test the minimal program (without the rest of your code)? I put the exact code I tested here: https://pastebin.com/aYzfPq8z – drescherjm Sep 16 '18 at 20:30
  • Yeah it is definitely something else that is messing with my code. Just tested your code and I get "macros" both with and without debugging. – Jacce Sep 16 '18 at 20:39
  • It could be some type of Undefined Behavior in the rest of your code causing this. There probably is nothing we can do to help / find it however my advice is to properly solve all warnings if you get any. – drescherjm Sep 16 '18 at 20:45

1 Answers1

0

Addressing why rand() behaves differently between in debug mode is a question for your compiler vendor. How it works internally is implementation-defined (i.e. up to the compiler's creators). From cppreference:

There are no guarantees as to the quality of the random sequence produced. [...] rand() is not recommended for serious random-number generation needs. It is recommended to use C++11's random number generation facilities to replace rand().

Clearly rand() is a bit old-fashioned, which I'll address toward the end of my answer. As to why you're seeing the same value during every run of the program, this is not a bug with rand(). rand() is a pseudo-random number generator that can generate seemingly random numbers, but in a completely deterministic manner. In order to get different results on every run, you need to seed the random number generator with something somewhat unpredictable, like, say, the current time. This is done as follows.

#include <cstdlib>
#include <ctime>
int main(){
    srand(time(0));
    // rand() will now behave differently on each run of the program
}

This is also explained here. It is also important to note that you should only call srand once at the start of your program. Calling srand multiple times within the same second will result in the same seed, and thus the same random sequence from rand, as explained here.


If you want to be most correct, C++11 now offers a good random number generation library that you should consider using. An example usage could look like:

#include <random>
std::random_device rd; // reliable random seed generator
std::default_random_engine randengine { rd() }; // global rng, seeded with random device

...

void Game::SelectHiddenWord(Fstring &word) {
    // NOTE: this vector can be static const if it never changes, to avoid
    // constructing and destructing it every function call
    static const std::vector<Fstring> WordList{ "plan","planet","planes","radios","gamers","images", "amigos","micros","macros","frogs","raids","roads","paris","smog","cars","macs","scam","some","farm","fair","jam","rat","map","zig","zag","isogram","amorist","roaming","mirages","soaring","cargos","disarm","isobar"};

    // define distribution as [ 0, WordList.size() )
    std::uniform_int_distribution<size_t> dist { 0, WordList.size() - 1 };
    word = WordList.at(dist(randengine));
}

I'm still a little confused by one thing you mentioned:

But I want the rand function to always generate the number 14 [...]

If this is really what you want, you can replace every rand() with 14 :-)

alter_igel
  • 6,899
  • 3
  • 21
  • 40
  • Well I am very new to programming in general and i'm trying to learn c++ so the reason I wanted it to generate the number 14 was really only for me to try to learn and understand how the language works. I am not planning on generating the number 14 every time when the program is done! :) – Jacce Sep 16 '18 at 20:31