Should rand() return a RAND_MAX value for 32 bit target?
Xi Ruoyao
xry111@mengyan1223.wang
Tue Sep 18 13:09:00 GMT 2018
On 2018-09-18 17:52 +0530, Neha Gowda wrote:
> Hi,
>
> I am trying to run the following testcase for Random Number Generator
> function.
> The testcase returns true when generated number is RAND_MAX and returns
> false when its not generated.
>
> Command :- gcc -m32 -O2 test.c
> ======================================================
> #include <stdio.h>
> #include <stdlib.h>
>
> int main()
> {
> unsigned int i;
> float f;
> srand(0);
> for (i = 0; i <= RAND_MAX; i++) {
> f = rand();
There is a rounding error introduced since a float can not represent
all integer values in [0, RAND_MAX].
> if (f == RAND_MAX) {
RAND_MAX is 2147483647 on 32-bit GNU/Linux. It can not be represented
by a float.
> printf("True\n");
> return 0;
> }
> }
> printf("False\n");
> return 1;
> }
> ======================================================
> Tried them on the latest source and observed that the RAND_MAX is generated
> when
> the optimization is not enabled. When optimization is enabled for 32 bit
> target RAND_MAX
> is not being generated. However, 64 bit generates RAND_MAX with or without
> optimization.
>
> On further investigation, I found that the expand phase is optimizing the
> following and hence
> the RAND_MAX value is not being generated.
> =========================================
> Replacing Expressions
> f_10 replace with --> f_10 = (float) _1;
> =========================================
>
> Can you please let me know if its the expected behavior or some bug?
See https://gcc.gnu.org/wiki/FAQ#PR323.
--
Xi Ruoyao <xry111@mengyan1223.wang>
School of Aerospace Science and Technology, Xidian University
More information about the Gcc-help
mailing list