Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using swap() without #including its library? [duplicate]

Tags:

c++

c++11

swap

I have a simple program in which I arrange the elements of an int array in ascending or descending order, and I use the swap() function to move the elements around. I compiled the program without any errors, and it ran like a charm. I only noticed afterwards that I had forgotten to #include the library that swap() is defined in (<algorithm>, or <utility> as of C++11) before I compiled.

Why did it still work? The top of my program looked like this:

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

I tried taking out <iostream>, just to see what would happen, and it predictably put out a bunch of 'cout/cin/endl' was not declared in this scope errors, but I was surprised to see that it gave some 'swap' was not declared in this scope errors as well. Does that mean swap() is defined in <iostream>? I don't think it should be, should it?

Anyways, this is probably a big long question for a simple answer, but I'm pretty curious. I'm still learning C and C++, so I don't know a lot of things, and I couldn't find an answer to this particular mystery via the "Almighty" Google Machine, so here I am.

Thanks in advance!

like image 689
Jasper Avatar asked Nov 02 '22 00:11

Jasper


1 Answers

Generally, do NOT rely on the header files that includes other header files.

Always include and only include the header files you need.

For example, if you want to use std::swap(), Google it and you'll see if requires <algorithm> in c++98 and <utility> in c++11, so you should include the file to make sure your code compiles.

like image 122
Mine Avatar answered Nov 15 '22 03:11

Mine