145

Coderbyte is an online coding challenge site (I found it just 2 minutes ago).

The first C++ challenge you are greeted with has a C++ skeleton you need to modify:

#include <iostream>
#include <string>
using namespace std;

int FirstFactorial(int num) {

  // Code goes here
  return num;

}

int main() {

  // Keep this function call here
  cout << FirstFactorial(gets(stdin));
  return 0;

}

If you are little familiar with C++ the first thing* that pops in your eyes is:

int FirstFactorial(int num);
cout << FirstFactorial(gets(stdin));

So, ok, the code calls gets which is deprecated since C++11 and removed since C++14 which is bad in itself.

But then I realize: gets is of type char*(char*). So it shouldn't accept a FILE* parameter and the result shouldn't be usable in the place of an int parameter, but ... not only it compiles without any warnings or errors, but it runs and actually passes the correct input value to FirstFactorial.

Outside of this particular site, the code doesn't compile (as expected), so what is going on here?


*Actually the first one is using namespace std but that is irrelevant to my issue here.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
bolov
  • 72,283
  • 15
  • 145
  • 224
  • Note that `stdin` in the standard library is a `FILE*`, and a pointer to any type converts to `char*`, which is the type of the argument of `gets()`. However, you should never, ever, ever write that kind of code outside an obfuscated C contest. If your compiler even accepts it, add more warning flags, and if you’re trying to fix a codebase that has that construct in it, turn warnings into errors. – Davislor Mar 21 '19 at 03:42
  • 1
    @Davislor no it doesn't "candidate function not viable: no known conversion from 'struct _IO_FILE *' to 'char *' for 1st argument" – bolov Mar 21 '19 at 10:14
  • 3
    @Davislor huh, that might be true for ancient C, but definitely not for C++. – Quentin Mar 21 '19 at 12:49
  • @Quentin Yeah. That shouldn’t compile. The intended challenge might’ve been, “Take this broken code, read my mind about what it’s supposed to do, and fix it,” but in that case there should be a real specification. With test cases. – Davislor Mar 21 '19 at 14:35
  • 6
    I’m surprised no-one tried this, but `gets(stdin )` (with an extra space) produces the expected C++ error. – Roman Odaisky Mar 21 '19 at 14:58
  • @RomanOdaisky we've already established that is a textual find and replace so no surprises there – bolov Mar 21 '19 at 17:21

3 Answers3

174

I'm the founder of Coderbyte and also the guy who created this gets(stdin) hack.

The comments on this post are correct that it is a form of find-and-replace, so let me explain why I did this really quickly.

Back in the day when I first created the site (around 2012), it only supported JavaScript. There was no way to "read in input" in JavaScript running in the browser, and so there would be a function foo(input) and I used the readline() function from Node.js to call it like foo(readline()). Except I was a kid and didn't know better, so I literally just replaced readline() with the input at run-time. So foo(readline()) became foo(2) or foo("hello") which worked fine for JavaScript.

Around 2013/2014 I added more languages and used third-party service to evaluate code online, but it was very difficult to do stdin/stdout with the services I was using, so I stuck with the same silly find-and-replace for languages like Python, Ruby, and eventually C++, C#, etc.

Fast forward to today, I run the code in my own containers, but never updated the way stdin/stdout works because people have gotten used to the weird hack (some people have even posted in forums explaining how to get around it).

I know it is not best practice and it isn't helpful for someone learning a new language to see hacks like this, but the idea was for new programmers to not worry about reading input at all and just focus on writing the algorithm to solve the problem. One common complaint about coding challenge sites years ago was that new programmers would spend a lot of time just figuring out how to read from stdin or read lines from a file, so I wanted new coders to avoid this problem on Coderbyte.

I'll be updating the entire editor page soon along with the default code and stdin reading for languages. Hopefully then C++ programmers will enjoy using Coderbyte more :)

yash
  • 1,357
  • 2
  • 23
  • 34
Daniel Borowski
  • 955
  • 1
  • 6
  • 3
  • 21
    "[B]ut the idea was for new programmers to not worry about reading input at all and just focus on writing the algorithm to solve the problem" - and it didn't occur to you to, instead of writing something that resembles "real" code, just put a made up function name or an obvious placeholder in that spot? Genuinely curious. – Ruther Rendommeleigh Mar 21 '19 at 08:48
  • Suppose that the input is a string instead of a number, let's say "hello". You replace `gets(stdin)` with "hello" and use that as input to the function to see if the test passes. If my code is wrong and it only passes with the string "world" as input, I can just put a `#define gets(string) "world"` and every test will pass. Right? – ChatterOne Mar 21 '19 at 09:59
  • 25
    I genuinely didn't expect I was going to choose an answer other than my own when I posted this. Thank you for proving me wrong in such a great way. It's really a pleasure to see your answer. – bolov Mar 21 '19 at 10:24
  • 4
    Very interesting! I would recommend, if you want to keep this hack, that you replace the function call with something like `TAKE_INPUT`, then use your find-replace to insert `#define TAKE_INPUT whatever_here` at the top. – Draconis Mar 21 '19 at 22:24
  • 18
    We need more answers starting with _"I'm the founder of x and also the guy who created this"_. – pipe Mar 22 '19 at 08:36
  • @RutherRendommeleigh what's an obvious placeholder? Hint, not all users of such sites are experienced programmers, so you'd need something that would be obvious to a noob so they know not to spend time rewriting it or thinking its wrong. Also, you need to come up with this for every single language you support. I'll check back on you in 7 years - it's only fair. – iheanyi Mar 22 '19 at 14:10
  • 1
    @iheanyi Something like `INPUT` or `__INPUT__` can work in many languages. And since there is some code in the first place it's possible to write a comment about such placeholder. – Andrew Svietlichnyy Mar 22 '19 at 18:35
  • @AndrewSvietlichnyy you're solving the problem with today's browsers and webservers, not the original problem the site faced. – iheanyi Mar 23 '19 at 19:03
  • 2
    @iheanyi No one asked for it to be perfect. In fact, I'm convinced that almost *any* placeholder would have been better than something that *looks* like valid code to any newbie but doesn't actually compile. – Ruther Rendommeleigh Mar 25 '19 at 08:24
  • @RutherRendommeleigh I disagree. Newbies would be confused by placeholders. They wont understand it's a placeholder. They're not confused by code that looks correct because they wont care. That's like a newbie being confused if there was a superfluous #include in C++ code - they'd simply not notice. – iheanyi Mar 26 '19 at 14:27
  • Even in 2012 you could take the input and create a script tag surrounding the "input" with "var INPUT = '" ... "';" – Will Crawford Nov 29 '19 at 08:46
113

I am intrigued. So, time to put the investigation goggles on and since I don't have access to the compiler or compilation flags I need to get inventive. Also because nothing about this code makes sense it's not a bad idea question every assumption.

First let's check the actual type of gets. I have a little trick for that:

template <class> struct Name;

int main() { 
    
    Name<decltype(gets)> n;
  
  // keep this function call here
  cout << FirstFactorial(gets(stdin));
  return 0;
    
}

And that looks ... normal:

/tmp/613814454/Main.cpp:16:19: warning: 'gets' is deprecated [-Wdeprecated-declarations]
    Name<decltype(gets)> n;
                  ^
/usr/include/stdio.h:638:37: note: 'gets' has been explicitly marked deprecated here
extern char *gets (char *__s) __wur __attribute_deprecated__;
                                    ^
/usr/include/x86_64-linux-gnu/sys/cdefs.h:254:51: note: expanded from macro '__attribute_deprecated__'
# define __attribute_deprecated__ __attribute__ ((__deprecated__))
                                                  ^
/tmp/613814454/Main.cpp:16:26: error: implicit instantiation of undefined template 'Name<char *(char *)>'
    Name<decltype(gets)> n;
                         ^
/tmp/613814454/Main.cpp:12:25: note: template is declared here
template <class> struct Name;
                        ^
1 warning and 1 error generated.

gets is marked as deprecated and has the signature char *(char *). But then how is FirstFactorial(gets(stdin)); compiling?

Let's try something else:

int main() { 
  Name<decltype(gets(stdin))> n;
  
  // keep this function call here
  cout << FirstFactorial(gets(stdin));
  return 0;
    
} 

Which gives us:

/tmp/286775780/Main.cpp:15:21: error: implicit instantiation of undefined template 'Name<int>'
  Name<decltype(8)> n;
                    ^

Finally we are getting something: decltype(8). So the entire gets(stdin) was textually replaced with the input (8).

And the things get weirder. The compiler error continues:

/tmp/596773533/Main.cpp:18:26: error: no matching function for call to 'gets'
  cout << FirstFactorial(gets(stdin));
                         ^~~~
/usr/include/stdio.h:638:14: note: candidate function not viable: no known conversion from 'struct _IO_FILE *' to 'char *' for 1st argument
extern char *gets (char *__s) __wur __attribute_deprecated__;

So now we get the expected error for cout << FirstFactorial(gets(stdin));

I checked for a macro and since #undef gets seems to do nothing it looks like it isn't a macro.

But

std::integral_constant<int, gets(stdin)> n;

It compiles.

But

std::integral_constant<int, gets(stdin)> n;    // OK
std::integral_constant<int, gets(stdin)> n2;   // ERROR                                          wtf??

Doesn't with the expected error at the n2 line.

And again, almost any modification to main makes the line cout << FirstFactorial(gets(stdin)); spit out the expected error.

Moreover the stdin actually seems to be empty.

So I can only conclude and speculate they have a little program that parses the source and tries (poorly) to replace gets(stdin) with the test case input value before actually feeding it into the compiler. If anybody has a better theory or actually knows what they are doing please share!

This is obviously a very bad practice. While researching this I found there is at least a question here (example) about this and because people have no idea that there is a site out there who does this their answer is "don't use gets use ... instead" which is indeed a good advice but only confuses the OP more since any attempt at a valid read from stdin will fail on this site.


TLDR

gets(stdin) is invalid C++. It's a gimmick this particular site uses (for what reasons I cannot figure out). If you want to continue to submit on the site (I am neither endorsing it neither not endorsing it) you have to use this construct that otherwise would not make sense, but be aware that it is brittle. Almost any modifications to main will spit out an error. Outside of this site use normal input reading methods.

Community
  • 1
  • 1
bolov
  • 72,283
  • 15
  • 145
  • 224
  • 28
    I'm genuinely amazed. Maybe this Q/A can be a canonical post on why not to learn from coding challenge sites. – alter_igel Mar 20 '19 at 20:07
  • 1
    The "8" comes from the left box at the bottom of the screen. Try typing a text string in there (I tried "maplemaple") and see the result... – Stobor Mar 20 '19 at 20:09
  • @Stobor yes, that is the "input" – bolov Mar 20 '19 at 20:09
  • 28
    Something really evil is happening, and I think it's at the level of text replacement in the source code outside of the compiler. Try this: `std::cout << "gets(stdin)";` and the output is `8` (or whatever you type into the 'input' field. This is a disgraceful abuse of the language. – alter_igel Mar 20 '19 at 20:13
  • @alterigel Yes it is - as I said, try putting text into the box, and you'll see it's directly substituted into the code, triggering an error in the original code... – Stobor Mar 20 '19 at 20:14
  • fwiw you can `#define gets(X) X`, use it in `main` eg as `gets(foo)`, get the expected error, and still the `gets(stdin)` works as not expected – 463035818_is_not_an_ai Mar 20 '19 at 20:15
  • 14
    @Stobor note the quotes around `"gets(stdin)"`. That's a string literal that even the preprocessor wouldn't touch – alter_igel Mar 20 '19 at 20:15
  • @alterigel - I think we're agreeing with each other. :) – Stobor Mar 20 '19 at 20:17
  • 2
    To quote James Kirk: "This is damn peculiar." – ApproachingDarknessFish Mar 21 '19 at 19:49
  • 2
    @alterigel get off your high horse. This is no statement to whether learning from coding challenge sites is useful or not. Who are you to decide how people practice stuff? – Matsemann Mar 22 '19 at 09:38
  • @Matsemann my comment was intended specifically at C++, and perhaps I should have made that clearer. I understand that coding challenge sites are very practical and extremely helpful for other languages like JavaScript or Python, but C++ is a highly nuanced, complex, and evolving language that is clouded with bad and misleading advice on the web. We have a [canonical post](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) about it. – alter_igel Mar 22 '19 at 15:12
65

I tried the following addition to main in the Coderbyte editor:

std::cout << "gets(stdin)";

Where the mysterious and enigmatic snippet gets(stdin) appears inside a string literal. This shouldn't possibly be transformed by anything, not even the preprocessor, and any C++ programmer should expect this code to print the exact string gets(stdin) to the standard output. And yet we see the following output, when compiled and run on coderbyte:

8

Where the value 8 is taken straight from the convenient 'input' field under the editor.

Magic code

From this, it's clear that this online editor is performing blind find-and-replace operations on the source code, substitution appearances of gets(stdin) with the user's 'input'. I would personally call this a misuse of the language that's worse than careless preprocessor macros.

In the context of an online coding challenge website, I'm worried by this because it teaches unconventional, non-standard, meaningless, and at least unsafe practices like gets(stdin), and in a manner that can't be repeated on other platforms.

I'm sure it can't be this hard to just use std::cin and just stream input to a program.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
alter_igel
  • 6,899
  • 3
  • 21
  • 40
  • and it's not even a blind "find and replace" because sometimes it replaces it sometimes it does not. – bolov Mar 20 '19 at 20:31
  • 4
    @bolov could it be just the first occurrence of `gets(stdin)` that is replaced? I meant 'blind' in the sense that it appears to be unaware of the language's syntax or grammar. – alter_igel Mar 20 '19 at 20:39
  • yes, you are right. It replaces the first occurence. I tried putting one before main and that's what I got indeed. – bolov Mar 20 '19 at 20:54
  • 1
    Further research suggests that that site does it for all languages, not just C++ - python/ruby it uses the function call ("raw_input()" or "STDIN.gets") which would typically return a string from stdin, but ends up doing a string substitution of that string instead. I guess finding a regex match for the getline function was too hard, so they went with gets(stdin) for C/C++. – Stobor Mar 20 '19 at 23:39
  • 4
    @Stobor dang, you're right. I can confirm this happens for Java too, the line `System.out.print(FirstFactorial(s.nextLine()9));` prints `89` even when `s` is undefined. – alter_igel Mar 20 '19 at 23:41