[Interest] How does one use Q_ASSUME?

Elvis Stansvik elvstone at gmail.com
Sun May 26 14:16:43 CEST 2019

Den sön 26 maj 2019 kl 12:37 skrev René J. V. Bertin <rjvbertin at gmail.com>:
> Giuseppe D'Angelo via Interest wrote:
> Hi,
> > On the other hand, Q_ASSUME(cond) tells the compiler that cond is true,
> After reading the MS doc I sort of understand how you can use the construct to
> implement a Q_UNREACHABLE (but in the example given I don't see the codegen
> advantage of `default: Q_UNREACHABLE` vs. not adding a `default:` at all).
> > Look here at a possible example at how it can improve codegen:
> >
> > https://gcc.godbolt.org/z/KlWBRY
> Not really, I'm afraid.
> The only thing that's evident to me from there is that there is much fewer
> generated machine code when you add the assume statement. I don't see at all why
> that would be, what difference it would make for the loop that it is always
> iterated over a multiple of 16. I thought the difference might be in evaluating
> the `i < count` expression, but even after trying to factor that out the
> difference remains:
> https://gcc.godbolt.org/z/2Zclp5
> Take home message for me is that this is a construct that's probably useful only
> if you have very intimate knowledge about code generation, and thus not very
> cross-platform/compiler (and even less cross-architecture). Except for the

Yes, I would also think it's something you bring out only for really
tight spots. And it is just a hint. The compiler is free to ignore it.

It is compiler specific like you say, but Q_ASSUME is not. It will
expand to the compiler specific hint on compilers that supports it,
else it'll just be an assert.

#define Q_ASSUME(Expr) \
    do {\
        const bool valueOfExpression = Expr;\
        Q_ASSERT_X(valueOfExpression, "Q_ASSUME()", "Assumption in
Q_ASSUME(\"" #Expr "\") was not correct");\
    } while (false)

(Q_ASSUME_IMPL will be the compiler specific hint, if supported, else a no-op)


> What I was hoping it might do is what the Qt documentation suggests, a more
> graceful version of a Q_ASSERT. That is, a version that does the usual abort in
> debug builds, but becomes a regular if in production code. I've seen too many
> examples of coding where a Q_ASSERT is used to guard against situations that are
> *assumed* never to occur, and then forgotten (or the devs assume everyone else
> uses debug/development builds). In many if not most of those cases it's trivial
> to add a graceful handling of the situation.
> R
> _______________________________________________
> Interest mailing list
> Interest at qt-project.org
> https://lists.qt-project.org/listinfo/interest

More information about the Interest mailing list