g++ supports two ways of calling a function from the std namespace

Hi there,

I'd like to know why is the following code correct according to g++:

1
2
3
4
5
6
7
8
#include <cstring>
#include <iostream>
 
int main()
{
    std::cout << strlen("Foo") << '\n'
              << std::strlen("Foo");
}


We call strlen functions without and preceded by the std:: prefix. Both of them produce the same output - "3". Is it somehow conformant to the C++ Standard? In my opinion the line with:

strlen("Foo")

should result in an error beacuse of the lack of the using directive.

Regards.
Last edited on
closed account (zb0S216C)
No, it doesn't. Initially, <cstring> includes <string.h> which defines "strlen( )" globally. The <cstring> header pulls that definition into the "std" name-space but the original definition of "strlen" is still globally defined for backwards compatibility for programs with a C base.

Compile this and see for yourself:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void Function( int X )
{
    std::cout << X;
}

namespace U
{
    using ::Function;
}

int main( )
{
    ::Function( 0 );
    U::Function( 1 );

    return( 0 );
}

Wazzak
Last edited on
the standard specifically allows implementations to include strlen( ) along with std::strlen() when <cstring> is included (same for all C library declarations) . Some compilers don't do it (Sun Studio for example), others do (GCC for example). Both are right, but a standard-compliant program won't attempt to use strlen
Last edited on
Topic archived. No new replies allowed.