Search code examples
cglib

g_random_int() returns negative numbers


This is the documentation of g_random_int() function from GLib:

 guint32 g_random_int (void);
 Return a random guint32 equally distributed over the range [0..2^32-1].

But the following code returns negative numbers:

 for (i=0; i< 10; ++i)
     printf("Random: %d\n", g_random_int());

Something obvious that I am missing.


Solution

  • The problem is in your printf-format string.

    %d is the format-specifier for signed integers.

    You are effectively reading the unsigned integer as if it was signed.

    Use %u instead :) Then your code becomes

     for (i=0; i< 10; ++i)
         printf("Random: %u\n", g_random_int());
    

    Here is a reference for the various format-specifiers in C: http://www.cplusplus.com/reference/cstdio/printf/

    EDIT

    I believe this is the passage in the C99 standard that describes the case of undefined behavior for the formatted output-functions, that @12431234123412341234123 refers to:

    In a call to one of the formatted output functions, a precision appears with a conversion specifier other than those described (7.19.6.1, 7.24.2.1).

    .. or maybe it's this:

    An invalid conversion specification is found in the format for one of the formatted input/output functions, or the strftime or wcsftime function (7.19.6.1, 7.19.6.2, 7.23.3.5, 7.24.2.1, 7.24.2.2, 7.24.5.1).

    See this page for more cases that are undefined behavior: https://gist.github.com/Earnestly/7c903f481ff9d29a3dd1

    EDIT2

    See the comment section for a much more intelligent discussion of the issue.