Reputation: 115
This question has no practical use! I've asked this only because I'm curious!
There is a way in C++ to falsify true as false by writing somewhere #define true false
, and then everywhere true
in code will considered as false
. But I'm seeking for a way to falsify true
as false
and false
as true
at the same time:
#define true false
#define false true
This doesn't works, and trying to "save" original true
also doesn't:
#define temptrue true
#define true false
#define false temptrue
Do you know any way to do that?
Upvotes: 1
Views: 264
Reputation: 70482
Perhaps something like this?
#define false static_cast<bool>(1)
#define true static_cast<bool>(0)
Regarding undefined behavior:
Those that say it is undefined are probably referring to the answer to this question: Is it legal to redefine a C++ keyword?
However, if you do not use the standard C++ library, the cited restriction does not apply (kudos to Bathsheba and Martin York).
16.5.4.1 [constraints.overview]
Subclause 16.5.4 describes restrictions on C++ programs that use the facilities of the C++ standard library.
...
16.5.4.3.2 [macro.names] ...
A translation unit shall not#define
or#undef
names lexically identical to keywords, ...
C++ 2020 draft
Upvotes: 3
Reputation: 234835
The behaviour on attempting to #define
a C++ keyword is undefined. Don't do it!
It's not quite so pretty, but
static constexpr bool true_ = false;
static constexpr bool false_ = true;
is probably the best you can do.
Upvotes: 2
Reputation: 1356
use constexpr
variables rather changing the behavior of true
and false
.
static constexpr bool TRUE = false;
static constexpr bool FALSE = true;
Upvotes: 1
Reputation: 545985
This obviously has no practical use whatsoever and is not valid C++, but the following does the trick:
static constexpr auto fake_true = false;
static constexpr auto fake_false = true;
#define true fake_true
#define false fake_false
Simply using numeric literals (e.g. 1 and 0) might appear simpler but will cause different semantics in situations where the type matters (e.g. overload resolution).
Upvotes: 1