26
1
This is the first of a series of C++ puzzles for you. Hope you will enjoy.
So, puzzle no.1:
Given the following program:
#include <iostream>
int main()
{
const int a=1;
const int b=2;
const float c=0.5;
std::cout << a/b-a*c;
}
Insert some code on a single new line anywhere inside the program so that the output will be 0. The new line will contain AT MOST 18 characters (including spaces), and the rest of the lines will remain unmodified. To be clear, here is an example of a valid new code:
#include <iostream>
int main()
{
const int a=1;
const int b=2;
int* p = NULL;
const float c=0.5;
std::cout << a/b-a*c;
}
A new line with 15 characters was inserted so it's ok. However it does not solve the problem.
If this is too simple for you, don't worry, more is coming!!
2I'm very happy someone posts a C++ question occasionally! I mean, with all the puzzles where a C++ solution would be 20 or 30 lines, then people posting solutions in J or K or Golfscript becomes frustrating after a while. – Mr Lister – 2012-09-28T17:59:18.363
3Does the result have to be valid, well-defined C++ or can it use UB? (But like Mr Lister noted, the original code isn’t even valid C++.) – Konrad Rudolph – 2012-09-28T18:28:51.730
@KonradRudolph - I don't know what IDE you use, I used DevC++ and it worked fine, so i wouldn't really say it's not valid C++ :) And the result has to be valid also, yes. – Bogdan Alexandru – 2012-09-28T19:38:10.203
4it is not valid. main must return int (read the c++ standard) – BЈовић – 2012-09-28T19:40:25.803
2we are missing the point here. put an int and a return 0 if you mind, I didn't. – Bogdan Alexandru – 2012-09-28T20:00:22.637
11@Bogdan: Dafuq? For one, DevC++ is so unspeakably ancient, it's output is irrelevant. And secondly, whether or not any given compiler in any given configuration at any time targetting any OS accepts it does not make it valid C++. – DeadMG – 2012-09-28T20:24:02.023
Nice task, but the limit of only 18 characters forbids a lot of creative solutions. What's the point? It's obvious that those short
#define
ones work, but they aren't really the most interesting ones, are they? – ceased to turn counterclockwis – 2012-09-29T01:37:58.5432While I find the idea very nice, there is no scoring criteria. – vsz – 2012-09-29T07:38:01.713
Hi everybody, thanks for all the feedback and the advice, since this was my first post I did make some mistakes (like ignoring the int and not mentioning 0 as the ONLY output) but I promise I'll learn out of your advice and next time it will be more precise! Cheers – Bogdan Alexandru – 2012-09-29T17:34:46.437
@leftaroundbout: I limited the size of the line because I wanted to deny the most obvious solution: std::cout<<0; exit(0); – Bogdan Alexandru – 2012-09-29T17:35:45.047
@BogdanAlexandru: Maybe it would be better to forbid it more explicitly, i.e. "the
main
function must run all of its body" or something? – FireFly – 2012-09-29T19:12:00.057