1

Screenshot

#include <iostream>
using namespace std;

int main() {
    // your code goes here
    cout << max(1, 5);
    return 0;
}

(Sorry for my bad English) Hi! I can't understand how it works. I'm not using algorithm header but it work. I test it on Visual Studio 2019, xcode and ideone.com. Please check the screenshot. Thank you.

2
  • 3
    A header like iostream (or any other header) can include further other headers, but there is no guarantee about which headers iostream might include or if this will change in future or for all std libs. So you should always include the header corresponding to the functions and classes you are about to use in the file directly. Commented May 1, 2020 at 9:56
  • 4
    Actually, it does not run on Visual Studio 2019 implementation. It can compile on GCC implementation as the <iostream> header there implicitly or explicitly includes the <algorithm> header somewhere. A rule of thumb is: if you need a header, include it, do not rely on the implementation. Commented May 1, 2020 at 9:57

1 Answer 1

1

Such things happen when a header internally includes another header whose function you're using.

In this case maybe the compilers you're using have implemented <iostream> in a way that it is including <algorithm>.

If you want your code to be portable, then you should never rely on how your compiler implements it. (You should rely on how the standard guarantees it.)

You should include each and every header file that is necessary.

Sign up to request clarification or add additional context in comments.

4 Comments

But one problem in this context, I've ran the same code given by the asker, that fails on VSCode. It throws namespace std has no member 'max'. I'm not sure why results are unexpected for both of us.
@LinuXMan I think you're getting the correct result. The code doesn't work on Visual Studio 2019 until and unless one hasn't changed the default compiler! Though it works on g++ and clang.
Oh wow, that's when I tried both using namespace std; and without implementing namespace, std::max(), both threw the same results.
@LinuXMan Actually VS Code and VS are two different things. I hope you meant the same or was using vc++ to build your code in VS Code. BTW it doesn't compiles for sure on MSVC compiler.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.