2

I noticed I managed to compiled the following code without inclusion of <string>. Shouldn't it be giving me an error?

#include <iostream>
 using namespace std;

struct Sales_data {
    string book_no;
    double units_sold;
    double price;
};

int main() {
    Sales_data book1, book2;
    cout << "Please enter first transaction in format: ISBN, units sold & price" << endl;
    cin >> book1.book_no >> book1.units_sold >> book1.price;
    cout << "Please enter second transaction in format: ISBN, units sold & price" << endl;
    cin >> book2.book_no >> book2.units_sold >> book2.price;

    cout << "******************************" << endl;
    cout << "Total units sold = " << book1.units_sold + book2.units_sold << endl;
    cout << "Total revenue = " << (book1.units_sold * book1.price) + (book2.units_sold * book2.price) << endl;
    return 0;
}

Compilation results:

[yapkm01][~/C++Primer/chapter2]# g++ -std=c++11 -o 2-41a 2-41a.cc
[yapkm01][~/C++Primer/chapter2]#
Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
yapkm01
  • 3,590
  • 7
  • 37
  • 62
  • 4
    `iostream` apparently includes `string` in your standard library implementation. This is incidental – include what you know you need. – ildjarn Jul 17 '16 at 18:20
  • "[yapkm01][~/C++Primer/chapter2]# g++ " - why are you compiling code as root? Not that it matters (much), just currious.. – Jesper Juhl Jul 17 '16 at 19:11
  • @JesperJuhl No. I am not compiling as root. I am using my id "yapkm01" to compile. – yapkm01 Nov 23 '16 at 20:04
  • @yapkm01 the hashmark (#) prompt in your question says otherwise ;-) "#" is used for the root user, normal users usually get a "$". "[yapkm01][~/C++Primer/chapter2]# g++ ..." – Jesper Juhl Nov 23 '16 at 21:59

2 Answers2

6

Shouldn't it be giving me an error?

It's implementation dependent. Some compiler implementations intrinsically #include <string> with the <iostream headers, others have forward declarations.

Always include the headers for any standard types you use. Multiple #include statements do no harm, and will be optimized using the appropriate header guards already.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
4

You should #include <string> since otherwise you have no guarantee that the prototype for std::string is available.

However, you seem to have gotten away with not doing so since, aparently, in your case, on your implementation, the iostream header seems to include string for you (directly or indirectly). You cannot, however, rely on this.

Always include what you use. Not doing so relies on implementation defined behaviour and is not portable.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70