0

In the docs, it's written:

int QRandomGenerator::bounded(int highest)

Note that this function cannot be used to obtain values in the full 32-bit range of int. Instead, use generate() and cast to int.

But generate() returns quint32.

So it looks like it's suggested to use static_cast<int>(QRandomGenerator::global()->generate()) and get a signed overflow and -- this way -- get a signed random 32bit integer. But is not a signed overflow an undefined behavior? Or do I understand anything wrong? What is a proper way to get a random int in Qt?

JenyaKh
  • 2,040
  • 17
  • 25
  • 1
    I think the value is implementation-defined if the `unsigned int` is not representable as an `int`. So it should work, but it may not be portable (i.e. may not give necessarily the same results with different compilers for example) – Fareanor Dec 12 '22 at 10:03
  • I am sorry I don't get it. I've read in many different places (e.g. https://stackoverflow.com/questions/16188263/is-signed-integer-overflow-still-undefined-behavior-in-c) that sign overflow is UB. Is not it? – JenyaKh Dec 12 '22 at 10:29
  • 1
    Yes but you're not doing signed integer overflow, you're doing integral conversions. And AFAIK `static_cast` from `unsigned int` to `int` is implementation-defined if the former is not represantable as the latter [(See here)](https://stackoverflow.com/a/7602006/11455384) I don't know if this rule changed (C++03 is old now) but if it still applies (I guess it is the case otherwise Qt would not recommend doing that), you can go with that. You don't care about the non-portable behaviour since you want a random anyway. – Fareanor Dec 12 '22 at 10:47

0 Answers0