1
#include <iostream>

int main() {

    std::string a="hello";
    std::cout<< a;
}

The above code prints out "hello". Then, why do people insist upon including the <string> header file?

Mr Lister
  • 45,515
  • 15
  • 108
  • 150

2 Answers2

9

There is no guarantee your code will work without <string>. That is the header std::string is defined in, so you must include it if you want your code to be portable.

Your code may work or appear to work because <iostream> directly or indirectly includes <string>.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • 1
    In at least some implementations, `` includes `basic_string` and its aliaces, but not additional string facilities, like `to_string` and `stoi`. Other implementation includes `basic_string`, but not its aliases, so declaring `basic_string` will work, but `std::string` won't. – Revolver_Ocelot Dec 20 '15 at 16:29
  • @Revolver_Ocelot: Wouldn't a forward-declaration for `std::basic_string` suffice for implementing that header? – Deduplicator Dec 27 '15 at 18:57
3

I think your compiler is just being nice to you. If you are using strings, you should #include <string>, whether or not your particular compiler lets you get away without it. Moreover, apparently <iostream> includes <string>, directly or indirectly, but don't rely on it.