-
Notifications
You must be signed in to change notification settings - Fork 126
C Interoperability and Type Casting
williamfgc edited this page May 4, 2017
·
7 revisions
-
Avoid mixing C headers, functions, and casting use corresponding C++ equivalent. Example: use
cmath
notmath.h
,iostream
notstdio.h
-
Don't
#include <stdio.h> #include <math.h> ... float powerOfTwo = powf( 2.f, 5.f ); printf( "2^5 = %f\n", powerOfTwo );
-
Do
#include <iostream> #include <cmath> ... constexpr float powerOfTwo = powf( 2.f, 5.f ); std::cout << "2^5 = " << powerOfTwo << "\n";
-
-
Exceptions for using C headers/functions:
- C++ API is deprecated or not fully supported in libraries ( e.g. MPI, CUDA_C, PETSc )
- No POSIX equivalent in C++: e.g.
unistd.h, shmem.h, sys/ipc.h
- Language Interoperability through C
C++ --> C --> Fortran --> C --> C++ C++ --> C --> JNI --> Java --> JNI --> C --> C++
-
Avoid C-style casting: use C++11 style casting:
static_cast, dynamic_cast (classes), reinterpret_cast
.-
Don't
int foo = ( int ) bar; char* buffer = ( char* ) data;
-
Do
int foo = static_cast<int>( foo ); char* buffer = reinterpret_cast<char*>( data );
-
Don't