Which library does strlen()
belong to?
Does it belong to cstring
? or string
?
I tried the following code, and it does work:
include <iostream>
using namespace std;
//withou include<string.h>
int main() {
char * str="abc";
cout<<strlen(str);
}
I set str
equal to 3 and give the right answer 3.
Why does it work without including library string or cstring?
Should I include cstring or string there? string.h?
Which library does strlen() belong to? Does it belong to cstring? or string?
Neither. cstring
and string
are not libraries, they are header files which define the interface to various functions and classes.
The C language standard says that the strlen
function is declared in the header file <string.h>
. In C++, including <string.h>
places strlen
into the global namespace, while including <cstring>
instead places strlen
into the std
namespace.
The actual implementation of the strlen
function is in the C standard library (aka libc
or CRT
on certain platforms). Ordinarily, this is linked in with your executable at link time.
Why it works without including library string or cstring?
In your particular compiler and toolchain, it just so happens that the header file <iostream>
includes <cstring>
into it, which means that any code that includes the former also gets the latter for free. This is an implementation detail and should not be relied upon—if your compile your code with another compiler, you may suddenly find yourself in a sea of compiler errors.
The proper thing to do is to also include <cstring>
here; even though it's not necessary with your particular compiler, it may be necessary with other compilers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With