2

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.

  • 2
    also #include – QuentinUK May 02 '22 at 06:30
  • 2
    When you include one header file from the standard library, that might in turn include other headers. The standard specifically says that it is allowed to do so. However, you should still include the headers you need, as you cannot know exactly how the headers are nested (and it might change). – BoP May 02 '22 at 06:34
  • @QuentinUK Thanks for pointing it out. Because of code formatting, It wasn't visible. Now corrected it. – Bhaskar Jha May 02 '22 at 08:07

1 Answers1

0

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.

Valence
  • 1
  • 1