328

I posted a question with my code whose only #include directive was the following:

#include <bits/stdc++.h>

My teacher told me to do this, but in the comments section I was informed that I shouldn't.

Why?

L. F.
  • 16,219
  • 7
  • 33
  • 67
Lightness Races in Orbit
  • 358,771
  • 68
  • 593
  • 989
  • 104
    Huh. I should have known there would be an include version of `using namespace std;` out there somewhere. – user4581301 Aug 05 '15 at 00:47
  • 2
    why does this header even exist? surely none of the standard includes actually include this, since it would bring in lots of junk? and if its not included by any of the public includes... then why is it shipped in the distribution? – Chris Beck Feb 01 '16 at 08:42
  • 13
    @ChrisBeck: It's an implementation detail. It's not part of the "public API" or meant for use. But it still has to be shipped otherwise nothing would work. The standard includes may not use it individually but it's there for use in precompiled headers. See the comment at the top, which says: _"This is an implementation file for a precompiled header."_. – Lightness Races in Orbit Feb 01 '16 at 10:41
  • 1
    @LightnessRacesinOrbit If you aren’t supposed to use it yourself, how does its existence help with PCH? Or is gcc smart enough to automatically switch over to it for PCH purposes in some circumstances? – Daniel H Nov 20 '17 at 18:22
  • @DanielH: Good question. Um, I don't know really, but that was probably what I was thinking yeah. Might be a good question in its own right. – Lightness Races in Orbit Nov 20 '17 at 19:12
  • 3
    @LightnessRacesinOrbit _"It's not part of the "public API" or meant for use."_ Entirely wrong, it's intended for public use, as a precompiled header. Libstdc++ (pre)compiles and installs a precompiled version of that header, so if you include it then G++ will actually include `bits/stdc++.h.gch` instead, the precompiled version. It exists because it has to exist so that the precompiled version of it can be generated. – Jonathan Wakely Aug 07 '19 at 16:00
  • 2
    @JonathanWakely The public API of the standard library, I mean; not of libstdc++. The people using it on Stack Overflow every day (and in their projects) are not using it for the reason, or in the use case, that you're talking about. Sure, my comment could have been worded more accurately, though note that I _did_ point out its use for precompiled headers. Feel free to write a competing answer. – Lightness Races in Orbit Aug 07 '19 at 16:06
  • Geeksforgeeks is spreading this. It has answers for technical interview coding rounds. Here is the reason. When you are solving a problem and writing code, you may start with a vector but then you think that map would be better. So everytime you change your mind, you have to update headers. One might miss that in rush. So it's a helpful here. Use should be discouraged in general programming though. – Aditya Singh Rathore Apr 20 '21 at 18:35

5 Answers5

378

Including <bits/stdc++.h> appears to be an increasingly common thing to see on Stack Overflow, perhaps something newly added to a national curriculum in the current academic year.

I imagine the advantages are vaguely given thus:

  • You only need write one #include line
  • You do not need to look up which standard header everything is in

Unfortunately, this is a lazy hack, naming a GCC internal header directly instead of individual standard headers like <string>, <iostream> and <vector>. It ruins portability and fosters terrible habits.

The disadvantages include:

  • It will probably only work on that compiler
  • You have no idea what it'll do when you use it, because its contents are not set by a standard
  • Even just upgrading your compiler to its own next version may break your program
  • Every single standard header must be parsed and compiled along with your source code, which is slow and results in a bulky executable under certain compilation settings

Don't do it!


More information:

Example of why Quora is bad:

iBug
  • 30,581
  • 7
  • 64
  • 105
Lightness Races in Orbit
  • 358,771
  • 68
  • 593
  • 989
  • 96
    "perhaps something newly added to a national curriculum in the current academic year" Blind leading the blind :( – Kuba hasn't forgotten Monica Sep 04 '15 at 22:24
  • Under certain compilation settings, however, the use of precompiled headers will reduce compilation time. Also, with standard out-of-the-box settings, I just compiled a trivial program with and without `#include ` and the difference in the size of the EXE file was 91 KB with, 89 KB without. – Evgeni Sergeev Apr 05 '16 at 07:53
  • 46
    Just came here through a wormhole in another question, very good. What makes this teaching habit worse is that it is usually followed by a direct `using namesapce std;`. Just two lines in and virtually every nice identifier is used. Incredibly frustrating to see it being taught. – StoryTeller - Unslander Monica Jun 27 '17 at 08:27
  • 9
    About the quora example, it might have shifted with time. I've visited the page today and both pros and cons of where listed in the specific context of online programming contests. I find their conclusion ok-ish. – YSC Feb 06 '18 at 14:47
  • The fourth bulletpoint is advantageous if precompiled headers are in use. [See here for explanation](https://stackoverflow.com/questions/4726155/whats-the-use-for-stdafx-h-in-visual-studio), this code is basically the gcc version of `#include "stdafx.h"` – M.M Jun 04 '18 at 21:29
  • 1
    @M.M: Not really - just because you're precompiling headers doesn't mean you need to precompile _every_ header – Lightness Races in Orbit Jun 12 '18 at 12:33
  • 8
    @EvgeniSergeev: 2KiB is *a lot* of code, data, symbol information, etc., when trying to determine its effect. Do you understand everything that is being added? For your compiler? The current release? All releases in between? All future releases? If you need to decide between convenience and correctness, there is only a single valid option. – IInspectable Aug 25 '18 at 07:48
  • 3
    Hopefully not a curriculum but rather just a cargo-cult spread across 'contest' websites or something... although sadly nothing would surprise me either way. – underscore_d Nov 19 '18 at 23:09
  • An heaven forbid you are using the pre-compiled headers option with it. Take a look at the size of the .pch file generated by VS under one of your repos/Debug (or Release) directories, They can be tens to hundreds of megabyes. – David C. Rankin Aug 04 '19 at 08:05
  • Devil's advocate. While all this is certainly true for professional code, you might make an argument that the include is acceptable for people using C++ to learn programming for the first time -- it lets them concentrate on their own code, and makes the teacher's grading job easier. The disadvantages (except your second bullet point to some extent) go away in a pedagogical situation. Frankly, the `using namespace std` makes me cringe more than the include. – Spencer May 21 '20 at 15:57
  • Lets have a new take on this please. All the points mentioned above are all very valid...however, shouldn't we fix all of them so we "can" actually just have 1 include line? Shouldn't our compiler do all the work to find the right header and include it if we wish? – Sujay Phadke Jun 24 '20 at 04:57
  • Updated link [C++ Standard - 16.5.1.2 Headers](http://eel.is/c++draft/headers) – David C. Rankin Aug 04 '20 at 17:35
  • 1
    @SujayPhadke> yes, the compiler should guess what the developer has in mind. Because of course there is only one function in the world named `distance`, the word `vector` certainly has no meaning outside of containers, … You're right a tool should help with this. But that's not a job for the compiler, that's the job of the IDE (and some of them indeed do it). – spectras May 14 '21 at 18:46
  • @spectras there's no need of sarcasm. There is no need to guess. By default the compiler just needs to have defaults configured. If you decide to change it for your purpose you can do it. By why should the 1000s of people have to keep writing this for their default use when 1 person changes the default behavior? – Sujay Phadke May 26 '21 at 12:45
  • @SujayPhadke finding things is simply not the job of the compiler. If something is not defined, it's not defined. Simple, clean, consistent, reliable, reproducible. I agree, having such things automated is great, and in fact many IDEs have this feature (bonus: it works for all libraries, not just the std one). There is no reason to introduce inconsistencies in the language and break design rules in the toolchain. – spectras May 26 '21 at 20:01
  • @SujayPhadke> are you really suggesting that the compiler should become configurable? And arguing that a small convenience that already exists in the proper tool (the IDE) is worth the complexity of making the compiler configurable and managing that configuration? Do you really not see how having configuration makes the behavior of the tool no longer consistent - it would only be consistent *given a specific configuration that needs to be managed, saved and archived*. Or is it just that you simply don't know the difference between your compiler and your IDE and which is responsible for what? – spectras May 27 '21 at 19:16
79

Why? Because it is used as if it was supposed to be a C++ standard header, but no standard mentions it. So your code is non-portable by construction. You won't find any documentation for it on cppreference. So it might as well not exist. It's a figment of someone's imagination :)

I have discovered - to my horror and disbelief - that there is a well-known tutorial site where every C++ example seems to include this header. The world is mad. That's the proof.


To anyone writing such "tutorials"

Please stop using this header. Forget about it. Don't propagate this insanity. If you're unwilling to understand why doing this is Wrong, take my word for it. I'm not OK being treated as a figure of authority on anything at all, and I'm probably full of it half the time, but I'll make an exception in this one case only. I claim that I know what I'm talking about here. Take me on my word. I implore you.

P.S. I can well imagine the abominable "teaching standard" where this wicked idea might have taken place, and the circumstances that led to it. Just because there seemed to be a practical need for it doesn't make it acceptable - not even in retrospect.

P.P.S. No, there was no practical need for it. There aren't that many C++ standard headers, and they are well documented. If you teach, you're doing your students a disservice by adding such "magic". Producing programmers with a magical mindset is the last thing we want. If you need to offer students a subset of C++ to make their life easier, just produce a handout with the short list of headers applicable to the course you teach, and with concise documentation for the library constructs you expect the students to use.

Kuba hasn't forgotten Monica
  • 88,505
  • 13
  • 129
  • 275
  • 1
    That well known site is that the one where every C++ example looks like a C program? – Surt Dec 20 '20 at 11:57
  • He is talking about GeeksForGeeks – SuperNoob Mar 15 '21 at 14:42
  • 1
    It will be fun when that header is included, along with `using namespace std;`. Then simple things like a user-defined [gcd](https://en.cppreference.com/w/cpp/numeric/gcd), [swap](https://en.cppreference.com/w/cpp/algorithm/swap) or variable named [data](https://en.cppreference.com/w/cpp/iterator/data) will act strangely or not compile at all, leaving the coder scratching their head as to what the issue could be. – PaulMcKenzie Apr 24 '21 at 09:58
  • I'm talking about the prototypical "well known site". There are, unfortunately, very many of them. And they all invariably look like blind leading the blind :( – Kuba hasn't forgotten Monica Apr 26 '21 at 12:54
50

There's a Stack Exchange site called Programming Puzzles & Code Golf. The programming puzzles on that site fit this definition of puzzle:

a toy, problem, or other contrivance designed to amuse by presenting difficulties to be solved by ingenuity or patient effort.

They are designed to amuse, and not in the way that a working programmer might be amused by a real-world problem encountered in their daily work.

Code Golf is "a type of recreational computer programming competition in which participants strive to achieve the shortest possible source code that implements a certain algorithm." In the answers on the PP&CG site, you'll see people specify the number of bytes in their answers. When they find a way to shave off a few bytes, they'll strike out the original number and record the new one.

As you might expect, code golfing rewards extreme programming language abuse. One-letter variable names. No whitespace. Creative use of library functions. Undocumented features. Nonstandard programming practices. Appalling hacks.

If a programmer submitted a pull request at work containing golf-style code, it would be rejected. Their co-workers would laugh at them. Their manager would drop by their desk for a chat. Even so, programmers amuse themselves by submitting answers to PP&CG.

What does this have to do with stdc++.h? As others have pointed out, using it is lazy. It's non-portable, so you don't know if it will work on your compiler or the next version of your compiler. It fosters bad habits. It's non-standard, so your program's behavior may differ from what you expect. It may increase compile time and executable size.

These are all valid and correct objections. So why would anyone use this monstrosity?

It turns out that some people like programming puzzles without the code golf. They get together and compete at events like ACM-ICPC, Google Code Jam, and Facebook Hacker Cup, or on sites like Topcoder and Codeforces. Their rank is based on program correctness, execution speed, and how fast they submit a solution. To maximize execution speed, many participants use C++. To maximize coding speed, some of them use stdc++.h.

Is this is a good idea? Let's check the list of disadvantages. Portability? It doesn't matter since these coding events use a specific compiler version that contestants know in advance. Standards compliance? Not relevant for a block of code whose useful life is less than one hour. Compile time and executable size? These aren't part of the contest's scoring rubric.

So we're left with bad habits. This is a valid objection. By using this header file, contestants are avoiding the chance to learn which standard header file defines the functionality they're using in their program. When they're writing real-world code (and not using stdc++.h) they'll have to spend time looking up this information, which means they'll be less productive. That's the downside of practicing with stdc++.h.

This raises the question of why it's worth taking part in competitive programming at all if it encourages bad habits like using stdc++.h and violating other coding standards. One answer is that people do it for the same reason they post programs on PP&CG: some programmers find it enjoyable to use their coding skills in a game-like context.

So the question of whether to use stdc++.h comes down to whether the coding speed benefits in a programming contest outweigh the bad habits that one might develop by using it.

This question asks: "Why should I not #include <bits/stdc++.h>?" I realize that it was asked and answered to make a point, and the accepted answer is intended to be the One True Answer to this question. But the question isn't "Why should I not #include <bits/stdc++.h> in production code?" Therefore, I think it's reasonable to consider other scenarios where the answer may be different.

RedGreenCode
  • 1,607
  • 1
  • 20
  • 31
  • 7
    I've upvoted already, but it might be worth pointing out that "for fun" is a good reason to take part in competitive programming. On the other hand "to impress a potential employers" is not - it will actively *harm* your case with me. – Martin Bonner supports Monica Apr 29 '19 at 08:32
  • 5
    @MartinBonner I know some hiring managers see competitive programming experience as a red flag. But as long as top software companies use CP-style problems in their interviews and run programming contests to find new recruits, CP will continue to be popular among aspiring developers. – RedGreenCode Apr 29 '19 at 15:46
  • @RedGreenCode I am not a manager (thank $DEITY), but I sometimes have influence on hireing desitions. And I *definitely* see any reference to "competitive programming" as a *huge* red flag - *not* an advantage. – Jesper Juhl Jul 23 '19 at 17:37
  • 8
    @JesperJuhl If technical interviewers at your company use algorithmic puzzles in their interviews (as many do), that gives candidates with competitive programming experience an advantage. Maybe the rational choice for candidates is to participate in CP but avoid mentioning it on their resume/CV. – RedGreenCode Jul 23 '19 at 23:41
  • 5
    While it's true that this header can find use in some competitive programming, it's not quite where it came from. It came from a classroom. And whoever taught in that classroom had enough influence to pollute - via cascade that followed - tens if not hundreds of thousands of students (by educating the teachers and peers who then, unwittingly, had been spreading that disease). And now those students are also writing tutorials in a go-to-place for tutorials. I just want to cry in a corner. Competitive programming sites should just have a **regex to reject any nonstandard header**. – Kuba hasn't forgotten Monica Apr 06 '20 at 03:23
  • @RedGreenCode Why is competitive programming a red flag?? It is better than someone who has no programming experience.... – Yunfei Chen Jul 08 '20 at 00:24
  • 3
    @YunfeiChen Some people believe it encourages bad habits (like using `#include ` or writing unreadable code) that the candidate would need to un-learn on the job. Having zero programming experience is also a red flag, but that's why we have interviews. – RedGreenCode Jul 08 '20 at 01:19
  • @RedGreenCode When I say zero coding experience I mean people who never worked in a programming job before, most university graduates have not worked in coding before. So they have nothing except for a degree certificate..... Hmm also why does coding competitions not care about effieciency I thought that was the whole point of the competition?? – Yunfei Chen Jul 08 '20 at 01:40
  • @YunfeiChen Coding competition scores are based on correctness, runtime speed, and coding speed (submission time). Using `bits/stdc++.h` only affects compilation speed and executable size, so it doesn't affect contest results. – RedGreenCode Jul 08 '20 at 03:09
  • @YunfeiChen> they also do not care (or even discourage) a lot of things that are very important for professional code. Readability, reusability, testability (of pieces), the ability to build upon existing wheels rather than reinventing it, … – spectras May 14 '21 at 18:55
  • @spectras well for reability, there's a reason why it is called coding golf, and all three of those factors are very subjective, this is no objective metric to measuring those so it should not be include as part of the criteria.... – Yunfei Chen May 16 '21 at 17:18
17

From N4606, Working Draft, Standard for Programming Language C++ :

17.6.1.2 Headers [headers]

  1. Each element of the C++ standard library is declared or defined (as appropriate) in a header.

  2. The C++ standard library provides 61 C++ library headers, as shown in Table 14.

Table 14 — C++ library headers

<algorithm> <future> <numeric> <strstream>
<any> <initializer_list> <optional> <system_error>
<array> <iomanip> <ostream> <thread>
<atomic> <ios> <queue> <tuple>
<bitset> <iosfwd> <random> <type_traits>
<chrono> <iostream> <ratio> <typeindex>
<codecvt> <istream> <regex> <typeinfo>
<complex> <iterator> <scoped_allocator> <unordered_map>
<condition_variable> <limits> <set> <unordered_set>
<deque> <list> <shared_mutex> <utility>
<exception> <locale> <sstream> <valarray>
<execution> <map> <stack> <variant>
<filesystem> <memory> <stdexcept> <vector>
<forward_list> <memory_resorce> <streambuf>
<fstream> <mutex> <string>
<functional> <new> <string_view>

There's no <bits/stdc++.h> there. This is not surprising, since <bits/...> headers are implementation detail, and usually carry a warning:

*  This is an internal header file, included by other library headers.
*  Do not attempt to use it directly. 

<bits/stdc++.h> also carries a warning:

*  This is an implementation file for a precompiled header.
Bulletmagnet
  • 4,416
  • 2
  • 22
  • 43
4

The reason we do not use:

#include <bits/stdc++.h>

is because of effiency. Let me make an analogy: For those of you who know Java: If you asked your instructor if the following was a good idea, unless they are a bad instructor they would say no:

import java.*.*

The #include... thing does the same thing basically... That's not the only reason not to use it, but it is one of the major reasons not to use it. For a real life analogy: Imagine you had a library and you wanted to borrow a couple of books from the library, would you relocate the entire library next to your house?? It would be expensive and ineffiecient. If you only need 5 books, well then only take out 5... Not the whole library.....

#include <bits/stdc++.h>

Looks convienent to the program look I only need to type one include statement and it works, same thing with moving a whole library, look I only need to move one whole library instead of 5 books, one by one. Looks convienent to you that is, for the person who actually has to do the moving?? Not so much, and guess what in C++ the person doing the moving will be your computer... The computer will not enjoy moving the entire library for every source file you write :).....

Yunfei Chen
  • 548
  • 5
  • 15