1
  1. I was writing a c++ code and came to use the 'strcmp' command, but I don't know if I should include the string.h library as in c.

  2. The c++ code used 'strcmp' without including the string.h library, but there was no error. Why didn't there be an error?

    Student* StdSearch(Student* pSt, char* name, int StdNum)    
    {   
        Student* find = 0;
    
        for (int i = 0; i < StdNum; i++)
        {
            if (strcmp((pSt + i)->StdName, name) == 0)
            {
                find = pSt + i;
                return find;
            }
        }
    
        if (find == 0)
            return NULL;
    }
8282gownj
  • 11
  • 1
  • 5
    First of all, if you're programming in C++ then rather use `std::string` than `char*` or `char` arrays. Secondly, for `std::strcmp` you should really include ``. It could be that some other header file already does that, but it's not something you can rely on. – Some programmer dude Apr 16 '21 at 12:52
  • 6
    "string.h" is not a library but a header. The compiler is not required to reject a program that does not include all the appropriate headers, it is only required to accept programs that do. – molbdnilo Apr 16 '21 at 12:52
  • 1
    You cannot rely on one standard header *not* having been included if you include any other standard header. – Caleth Apr 16 '21 at 13:00
  • 1
    `#include `, typically. It needs to know what a string looks like, so #includes a bunch of headers by itself. Makes you lose ten minutes of your life when you refactor the code. – Hans Passant Apr 16 '21 at 13:02
  • 4
    The C++ standard requires support of a significant proportion of the C standard library. There are some parts of the C standard library (and associated headers) that are not supported in C++ at all. A number of C standard headers have C++ counterparts (e.g. `` in C, `` in C++) and usage of several C standard headers and functionality they provide are deprecated in the C++ standard - meaning they are slated for removal in some future evolution of the C++ standard. – Peter Apr 16 '21 at 13:10
  • By "no error", do you mean that the compiler didn't issue an error, or there was no error when you ran the program? – John Bode Apr 16 '21 at 14:42

1 Answers1

1

I was writing a c++ code and came to use the 'strcmp' command, but I don't know if I should include the string.h library as in c.

You should include #include <cstring> to use strcmp in C++. The convention is that some C standard headers can be included into C++ by removing .h and prepending c like <cstdio> <cstdlib> <cstdint> etc.

Why didn't there be an error?

It is allowed, but not required, that standard headers include themselves. So it can be that you do #include <iostream> and iostream includes cstring or similar. It may work on your computer right now, but may fail with an update or on someone else's pc. To be sure that the symbol is visible, include the header with the symbol.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111