C++ Logo

std-proposals

Advanced search

P2264 Make assert() macro user friendly for C and C++

From: <stefan.cpp_at_[hidden]>
Date: Thu, 08 Apr 2021 12:14:21 +0200
­­Dear all,

I am somewhat unhappy with P2264R0. Its main goal is to make it more beginner friendly. However, it introduces a pitfall for beginners that is currently not present.

The paper suggests to define basically
#define assert(...) ((__VA_ARGS__)?(void)0:std::abort())
Certainly, it makes
 assert(std::is_same::value);
working as expected, which is good. However, a beginner might think that assert works like static_assert and write
 assert(std::is_same::value, "Different types");
If P2264R0 gets adopted, this becomes a well-formed. And the assertion will pass since a string literal is not NULL. Currently such a code is ill-formed, which is much better.

An alternative would be to define
#define assert(...) (bool(__VA_ARGS__)?(void)0:std::abort())
since a function style cast does not allow a comma operator. In this case,
 assert(std::is_same::value);
would work as expected and
 assert(std::is_same::value, "Different types");
would still be ill-formed.

The example from P2264r0
    assert((void)"this cannot be true", -0.0);
looks like an anti-pattern to me. Particularly after deprecating the comma operator in subscript expressions, it is very odd if it gets newly introduced into the assert macro. If WG21 accepts P2264r0 as-is into the standard and if programmers start using this comma operator trick (since it would be an allowed use), the above-mentioned pitfall will be stuck in the language forever.

PS: I have tried to post this e-mail some time ago, but apparently there was a problem.

Best regards,

­
Stefan




Ihr Recht auf Privatsphäre. Schützen Sie Ihre Daten und wechseln jetzt zu eclipso Mail & Cloud.

Received on 2021-04-08 05:14:25