Why can you use C code with C++

hi guys,

the title says it all but I'll elaborate a little,how is it possible to use C code in C++,for example we can use the standard C library and call other functions from other C libraries such as memset,memcpy,printf,puts etc

I always wondered how is this possible don't C++ and C use different compilers

thanks

The reason is that C++ supports most C syntax.
See https://en.cppreference.com/w/cpp/language/language_linkage

Note that even when C language linkage is used, the syntax and semantics of C++ do not change.

For instance:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
extern "C" int foo( unsigned int* pu ) // this function can be called from C code
{
    // int* pi = pu ; // though valid C, this is an error in C++

    int* pi = reinterpret_cast<int*>(pu) ; // fine, valid C++

    if( pi != nullptr ) // fine, C++
    {
        int& lvr = *pi ; // fine, C++
        return [lvr] ( auto x ) { return lvr+x ; }(2) ; // fine, C++
    }

    return 0 ;
}
Topic archived. No new replies allowed.