Hello CodeForces community!
Recently I've recalled one interesting C++ problem. In short: is it possible to write functions action
and cond
in such a way, so that the following code snippets work differently:
// Snippet #1:
action();
while (cond()) {
action();
}
// Snippet #2:
do {
action();
} while (cond());
More formally: suppose you're given the following three files:
You're only allowed to modify common.h
. You have to do that in such a way, so that Action
word is printed different amount of times by execution of main_while.cpp
and main_do_while.cpp
.
One of the possible solutions (try to think yourself before opening the spoiler!):
Share your solutions in the comments and don't forget to hide them under the spoilers! It would be interesting to see something smarter (e.g. solution which will work in any language with analogues of while
and do-while
)
Solution without macros:
It uses this magic, which is legal as of C++ 14. The link also contains workarounds if your compiler doesn't support this code.
An alternative solution (which doesn't pollute the namespace with the
do
replacement):A different idea:
A shorter solution (the two snippets "work" differently: the second one compiles, whereas the first one doesn't):