Reputation: 1187
I have a C++ program in this fashion
#include<iostream>
string A();
string B();
string C();
int main()
{
return 0;
}
I want to test an application by using the three functions A(),B() and C() in such a way that I call them randomly from the main() and in this way I test the application. I do not know if there exists any provision or any tweak which will allow me calling the the functions in any order randomly.
Is it possible in C++ to call functions randomly, if yes then what is the best way of doing it ?
Upvotes: 3
Views: 3522
Reputation: 308392
If the functions all have the same signature, you can make an array of function pointers.
typedef string (*func_ptr)();
func_ptr funcs[3] = { A, B, C };
cout << funcs[rand() % 3]() << endl;
Upvotes: 5
Reputation: 25165
Using C++11:
std::vector<std::function<std::string()>> functions = {a, b, c};
std::cout << functions[rand() % functions.size()]() << std::endl;
Upvotes: 2
Reputation: 1047
If your functions have the same signature:
Declare an array of functions
returnType (*p[3]) (type1 x, type2 y, ...);
Initialize the seed of the random number generator:
srand (time(NULL));
Call the functions as many times as you want in a loop:
for(i=0; i < MAX_TIME; i++)
p(rand() % 2);
Upvotes: 2
Reputation: 2744
Put all the functions in a function array:
string(*functions[3])() = { A, B, C };
and then call one randomly by its index:
int main()
{
(*functions[rand() % 3])();
}
Upvotes: 3
Reputation: 4939
How about a for loop selecting a random number to control which test is called.
for(size_t i = 0; i<NUM_Of_TESTS; ++i) {
switch(rand() % 3) {
case 0: A(); break;
case 1: B(); break;
case 2: C(); break;
}
}
A switch statement like this would allow for varying function signatures.
Upvotes: 10