1

I've been puzzled by this for a while. To test this out, I made a simple program that just creates a std::string variable and prints it out to the screen. However, it doesn't include <string.h>.

#include <iostream>

using namespace std;

int main()
{
        string name = "Test";
        cout << name << endl;
        return 0;
}

What confuses me is that this program compiles and runs perfectly. Right now I'm using the clang compiler that came with the XCode Developer Tools. Is this intended behavior? I hope this question isn't too ridiculous since I just started learning C++.

Geno C
  • 1,401
  • 3
  • 11
  • 26
mochimochi
  • 23
  • 4
  • 1
    `` includes `` – Barmar Aug 07 '20 at 00:47
  • 3
    @Barmar It *can* include it. – François Andrieux Aug 07 '20 at 01:13
  • 2
    Related question form Software Engineering: [Is it good practice to rely on headers being included transitively?](https://softwareengineering.stackexchange.com/questions/262019/is-it-good-practice-to-rely-on-headers-being-included-transitively) – user4581301 Aug 07 '20 at 01:17
  • C++-specific version: [Should I include every header?](https://stackoverflow.com/questions/26611481/should-i-include-every-header) – user4581301 Aug 07 '20 at 01:19
  • 2
    Note: doesn't seem to be directly related to he answer to your question, but it's important to note that the proper header in C++ is `` not ``. –  Aug 07 '20 at 02:16
  • @FrançoisAndrieux And obviously in this case it *does*. – Barmar Aug 07 '20 at 14:09
  • 1
    @Barmar It does, but the comment wasn't "`` includes `` in this case". I thought it best to specify that this is not a fact about the language. – François Andrieux Aug 07 '20 at 14:16

2 Answers2

1

The reason you do not need to include the #include <string.h> header file is because when you include the #include <iostream> header file it includes std::string.

However, do not rely on it. What may work on your compiler may not work on another. Always include the proper header files.

To edit your example this is how you should use it:

#include <iostream>
#include <string>


int main()
{
        std::string name = "Test";
        std::cout << name << std::endl;
        return 0;
}

Also note: why you should not use using namespace std;.

Geno C
  • 1,401
  • 3
  • 11
  • 26
-1

Why does my program compile successfully if I don't include <string.h>?

Because you don't use any definition / declaration from <string.h>.

program compiles and runs perfectly ... Is this intended behavior?

It is incidental behaviour.

There are no guarantees that one standard header wouldn't include other standard headers. It just so happens that <iostream> included <string> in this particular version of the standard library. Since there is no guarantee for this, it would be a mistake to rely on such transitive inclusion.

eerorika
  • 232,697
  • 12
  • 197
  • 326