Why even without explicitly including particular library of c++ as header file, the function invocation of that library properly gives output?

Viewed 61

I am learning programming in c++ and using vs code editor. Many times I read in tutorials that a particular function of stl is of this header file. For example toupper() is in the header<cctype>. Hence, when I have to use that particular function, I should include that header file in the source code. But, I have multiple times that even without including a proper header file of any function, the function works properly and gives output for some functions while for others it doesn't. For example: in the case of toupper() and putchar() it works, but in the case of sqrt() and many others, it doesn't.

#include<iostream>
#include<cmath>

int main() {
    int a, b;
    std::string c;
    char ch;
    a = 25;
    b = 21;
    c = "bk";
    ch = 'y';
    std::cout << "maximum of a and b is " << std::max (a,b) << std::endl;
    std::cout << "minimum of a and b is " << std::min(a, b) << std::endl;
    std::cout << "square root of a is " << std::sqrt(a) << std::endl;
    std::cout << "length of string stored in c is " << c.length() << std::endl;
    std::cout << "Upper of char stored in ch is " << char(toupper(ch)) << std::endl;
    putchar(toupper(ch));
    return 0;
}

I tried to find the process using ctrl + F12 and I saw what it looked that putchar() or toupper() was getting included implicitly from the compiler. If so then why not for functions like sqrt().

And also follow on question: Since I am a beginner learning C++, hence I don't want implicit inclusion, can I force vs code for explicit inclusion of header files and run only functions inside explicitly included header files?

A detailed explanation will be appreciated.

1 Answers

In MSVC, the string header contains:

// The <cctype> include below is to workaround many projects that assumed
// <string> includes it. We workaround it instead of fixing all the upstream
// projects because <cctype> is inexpensive. See VSO-663136.
#include <cctype>

So cctype is included from string in your case.

Related