BekzhanKassenov's blog

By BekzhanKassenov, history, 8 years ago, translation, In English

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:

common.h
main_while.cpp
main_do_while.cpp

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!):

Dirty hack

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)

  • Vote: I like it
  • +32
  • Vote: I do not like it

»
8 years ago, # |
  Vote: I like it +26 Vote: I do not like it

Solution without macros:

common.h

It uses this magic, which is legal as of C++ 14. The link also contains workarounds if your compiler doesn't support this code.

»
8 years ago, # |
  Vote: I like it 0 Vote: I do not like it
Spoiler