I want to do something evil. I want to override for loops to change the conditional. Is there any way to do this?
The GCC documentation supports keyword overrides: http://gcc.gnu.org/onlinedocs/cpp/Macros.html
What I'm trying to do is make a โprobabilisticโ wrapper for C ++ to see if I can do anything interesting with it.
#include <iostream> #include <cstdlib> #define P 0.85 #define RANDOM_FLOAT ((float)rand()/(float)RAND_MAX) #define RANDOM_CHANCE (RANDOM_FLOAT < P) #define if(a) if((a) && RANDOM_CHANCE) #define while(a) while((a) && RANDOM_CHANCE) // No more for loops or do-while loops #define do #define goto // Doesn't work :( //#define for(a) for(a) if(!RANDOM_CHANCE) { break; } int main() { srand(time(NULL)); //Should output a random list of Y and N's for(int i=0; i < 100; ++i) { if(i < 100) { std::cout << "Y"; } else { std::cout << "N"; } } std::cout << std::endl; // Will loop for a while then terminate int j = 0; while(j < 100) { ++j; std::cout << j << "\n"; } std::cout << std::endl; return 0; }
Perhaps a more legitimate use would be to count the number of loop iterations in a running program, for example, by matching
for(int i=0; i < 10; ++i)
to
for(int i=0; i < 10; ++i, ++global_counter)
Is it possible to accomplish what I'm trying to do?
EDIT: Thanks for the answers - I really appreciate that!
One of the things I can do with this is to simulate a fair coin (effectively making P equal to 0.5), noting that if you have a biased coin, Pr (HT) == Pr (TH). I did not find this trick, but it is useful. This means that you can approximate any probability distribution for P.
bool coin() { bool c1 = false; bool c2 = false; if(true) { c1 = true; } if(true) { c2 = true; }
source share