Can I control exactly what a function returns (i.e. rand()) when debugging?

Viewed 124

Say I have the following lines of code:

int a = rand();
int b = rand();
int c = rand(); 

Is there any way, when debugging, to make it so that 'rand()' will return, say, 1, then 2, then 3 to variables a, b, and c, respectively?

If not (which I assume is likely the case), is there an easy Ctrl-F replacement method where I can hardcode in these values when debugging?

2 Answers

One option is to use a preprocessor macro to 'override' the rand function, and compile with -DDEBUG.

#ifdef DEBUG
#define rand() debug_rand()
static int debug_rand() {
    static int n = 1;

    return n++;
}
#endif

Depending on the complexity of your project you may want to control the scope of this with additional #ifdef and #undef conditionals.


Alternatively, you could conditionally adjust your srand call.

#ifdef DEBUG
    srand(1);
#else
    srand(/* your usual seed gen */); 
#endif

What this does is cause your program to behave predictably.

You could write a separate program to map out the default set of values returned by N rand() calls on your system, and use that as a reference sheet.

What you want to do is called mocking

Is there any way, when debugging, to make it so that 'rand()' will return, say, 1, then 2, then 3 to variables a, b, and c, respectively?

Depends. Usually, you call srand(<seed>); once in your program. If you're ok with calling it each time before a rand() call you can find a seed that gives the desired output and call srand with that seed.

If the question is "Can I find a seed that gives this particular sequence in the beginning?" the answer is that it may be easy or hard depending on the length of the sequence.

Another option for debugging is to simply define your own random function while you're debugging. Like in Oka's answer

Related