dimanche 10 juillet 2022

Is std::equal guaranteed to short circuit?

I would like to compare a nul-terminated string against a string literal. I hope to use std::equal and am curious if this code is well-defined according to the C++ standard:

#include <algorithm>

bool is_foo(const char *str) {
    const char *lit = "foo";
    return std::equal(lit, lit + 4, str);
}

If std::equal is guaranteed to stop at the first mismatch, then this code seems defined to me even if str has length < 3. If there is no such guarantee then I think this may dereference past the end of str resulting in UB.

What if anything does the C++ spec say about this? Thanks for any help!

Aucun commentaire:

Enregistrer un commentaire