- You're given the following program:
--------------------------------
int main()
{
printf("TWO\n");
return 0;
}
---------------------------------
Add any code above or below the lines so that the output is
ONE
TWO
THREE
Give 10 different ways to do this and which of them are specific to C++?
: just comment it out (already mentioned)
#include <iostream>
int main() { std::cout << "ONE\nTWO\nTHREE\n"; return 0; }
/*
...
*/
2: use #if or #ifdef
#include <iostream>
#ifdef foo
...
#else
int main() { std::cout << "ONE\nTWO\nTHREE\n"; return 0; }
#endif
3: redefine printf (already mentioned)
#include <iostream>
#define printf(foo) std::cout << "ONE\n" << foo << "THREE\n";
...
4: overload printf (already mentioned, c++ specific)
void printf(const char * s);
...
#include <iostream>
void printf(const char * s) { std::cout << "ONE\n" << s << "THREE\n"; }
5: template printf (c++ specific)
void foo(const char * s);
template<typename T> void printf(T s) { foo(s); }
...
#include <iostream>
void foo(const char * s) { std::cout << "ONE\n" << s << "THRE\n"; }
6: redefine main
#include <iostream>
int foo();
int main() {std::cout << "ONE\n"; foo(); std::cout << "THREE\n"; return 0; }
#define main foo
...
7: put main in a namespace (c++ specific)
#include <iostream>
namespace foo {
...
};
int main() { std::cout << "ONE\n"; foo::main(); std::cout << "THREE\n"; return 0; }
8: put main in a class or struct (c++ specific)
#include <iostream>
struct foo {
...
};
int main() { foo bar; std::cout << "ONE\n"; bar.main(); std::cout << "THREE\n"; return 0; }
9: use #define to remove keywords
#include <iostream>
int main() {
printf("ONE\n");
#define main() do
#define return
#define int
...
while (!printf("THREE\n"));
#undef return
return 0;
}
10: abuse a class or struct constructor (c++ specific)
struct printf { printf(const char * s); };
...
#include <iostream>
printf::printf(const char * s) { std::cout << "ONE\n" << s << "THREE\n"; }