It's not entirely clear what the problem is.
The solution you have tried will not work because it is a macro-built
method of generating C code that generates a pseudo random number
sequence, for use in blocks of C code. The generated code contains
assignments to C variables and for that reason of course is illegal within preprocessor
directives: the preprocessor does not have variables or assignments.
You say you don't know how to take the modulus 4 of a large random number,
using the preprocessor, even assuming you can get one in a preprocessor
directive, and perhaps this difficulty is illustrated by:
#if KISS / 4 == 1
That is not how to get the modulus 4 of KISS
: it is equivalent to
#if KISS == 4
KISS
modulo 4 is KISS % 4
and the way to test in a preprocessor
directive if KISS
is a multiple of 4 is:
#if (KISS) % 4 == 0
The question title mentions no requirement that the random
value should be generated using the preprocessor only, but within
the post you ask how it can be done using only the preprocessor. If the
objective is simply to generate a compiler warning roughly one time
in 4 then I cannot see why the preprocessor alone should be used to
achieve this and I lean to the view that you have wrongly concluded that it must be
from the fact that the compiler warning must be triggered by a
some preprocessor #if
-test.
The obvious course is to have your build process - make
or
whatever - generate a random number with a range of 4 and pass this
value as a commandline macro definition to the compilation of the
source file in which the warning is to be sporadically generated.
You don't say what operating system you are working on, but to
illustrate for ubuntu using shuf
as the RNG:
main.cpp
#if (FORTUNE) % 4 == 0
#warning Whoops!
#endif
int main()
{
return 0;
}
Some builds:-
$ g++ -DFORTUNE=$(shuf -i 1-4 -n 1) main.cpp
main.cpp:2:2: warning: #warning Whoops! [-Wcpp]
#warning Whoops!
^
$ g++ -DFORTUNE=$(shuf -i 1-4 -n 1) main.cpp
$ g++ -DFORTUNE=$(shuf -i 1-4 -n 1) main.cpp
main.cpp:2:2: warning: #warning Whoops! [-Wcpp]
#warning Whoops!
^
$ g++ -DFORTUNE=$(shuf -i 1-4 -n 1) main.cpp
$ g++ -DFORTUNE=$(shuf -i 1-4 -n 1) main.cpp
main.cpp:2:2: warning: #warning Whoops! [-Wcpp]
#warning Whoops!
^
$ g++ -DFORTUNE=$(shuf -i 1-4 -n 1) main.cpp
$ g++ -DFORTUNE=$(shuf -i 1-4 -n 1) main.cpp
$ g++ -DFORTUNE=$(shuf -i 1-4 -n 1) main.cpp
$ g++ -DFORTUNE=$(shuf -i 1-4 -n 1) main.cpp
$ g++ -DFORTUNE=$(shuf -i 1-4 -n 1) main.cpp
main.cpp:2:2: warning: #warning Whoops! [-Wcpp]
#warning Whoops!
^
$ g++ -DFORTUNE=$(shuf -i 1-4 -n 1) main.cpp
$ g++ -DFORTUNE=$(shuf -i 1-4 -n 1) main.cpp
main.cpp:2:2: warning: #warning Whoops! [-Wcpp]
#warning Whoops!
^
If you use that shuf
command then the random value will always be in the range [1-4], so
your test could simply be #if FORTUNE == 4
, but
the modulo test will allow you to use any other RNG.