E
Eric Sosman
Ravi said:#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
void print_int(int value) {
char buff[1 + (sizeof value * CHAR_BIT + 2) / 3 + 1];
char *p;
do {
p = buff;
if (value < 0)
*p++ = '-';
while (p < buff + sizeof buff - 1)
*p++ = 10.0 / (RAND_MAX + 1.0) * rand() + '0';
*p = '\0';
} while (strtol(buff, &p, 10) != value || *p != '\0');
puts (value);
}
If I call your function with parameter 2999;
It goes to infinite loop ???
Depends on the quality of the rand() implementation.
If you run it long enough, it should eventually generate
the string "00000...02999" and determine that it's the
right answer. Let's see: Assuming a 32-bit `int' there
will be twelve digits. Each of these will be generated
"correctly" with probability 1/10, so the probability of
that the desired string is generated on any given pass
of the outer loop is 1e-12. On the average, then, it
will take about 1e12 ("one trillion" U.S.; "one billion"
U.K.) loops to determine the answer. Somewhere between
one and three hours, I'd guess, on a fast machine.
Of course, if rand() is deficient you might need to
wait a little longer ...
I get lot of warnings as well on GCC.
I only got one warning using "-Wall -W -ansi -pedantic"
but it was an important warning: the function should have
ended with puts(buff) rather than puts(value). That's
what I get for just typing things in free-hand.